Title Link: Symmetric Tree
Given a binary tree, check whether it is a mirror of the itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4
But the following are not:
1 / \ 2 2 \ \ 3
Note:
Bonus points if you could solve it both recursively and iteratively.
Confused what "{1,#,2,3}" means? > read more about how binary tree was serialized on OJ.
OJ ' s Binary Tree serialization:
The serialization of a binary tree follows a level order traversal, where ' # ' signifies a path terminator where no node ex Ists below.
Here's an example:
1 / \ 2 3 / 4 \
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
The requirement of this question is to judge whether a tree is symmetrical.
The idea of recursion, similar to the same Tree, is only here to judge symmetry.
The two subtrees trees L and R symmetric, that is, the nodes of L and R are the same, and the right subtree of Zuozi and R is symmetric and the right subtree of L and the left subtree of R are symmetric.
Time complexity: O (N)
Space complexity: O (1)
1 class Solution2 {3 Public:4 BOOL Issymmetric(TreeNode *Root)5 {6 if(Root == NULL)7 return true;8 return Issymmetric(Root - Left, Root - Right);9 }Ten Private: One BOOL Issymmetric(TreeNode *L, TreeNode *R) A { - if(L != NULL && R != NULL) - return L - Val == R - Val the && Issymmetric(L - Left, R - Right) - && Issymmetric(L - Right, R - Left); - Else - return L == NULL && R == NULL; + } - };
As for the method of iteration, not to be continued ...
Reprint please indicate source: Leetcode---101. Symmetric Tree
Leetcode---101. Symmetric Tree