题目链接:Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}" means? > read more on how binary tree is 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 exists below.
Here‘s an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
这道题的要求是判断一棵树是否是对称的。
采用递归的思路,类似Same Tree,只不过这里是判断对称。
两棵子树l和r对称,也就是l和r的节点数字相同,而且l的左子树和r的右子树对称 而且 l的右子树和r的左子树对称。
时间复杂度:O(n)
空间复杂度:O(1)
1 class Solution
2 {
3 public:
4 bool isSymmetric(TreeNode *root)
5 {
6 if(root == NULL)
7 return true;
8 return isSymmetric(root -> left, root -> right);
9 }
10 private:
11 bool isSymmetric(TreeNode *l, TreeNode *r)
12 {
13 if(l != NULL && r != NULL)
14 return l -> val == r -> val
15 && isSymmetric(l -> left, r -> right)
16 && isSymmetric(l -> right, r -> left);
17 else
18 return l == NULL && r == NULL;
19 }
20 };
至于迭代的方法,未完待续。。。