leetcode-101-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
3
4
5
1
/ \
2 2
/ \ / \
3 4 4 3

But the following is not:

1
2
3
4
5
1
/ \
2 2
\ \
3 3

分析


meh

解决方案1(C++)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
return root==NULL || isEqual(root->left, root->right);
}
private:
bool isEqual(TreeNode* left, TreeNode* right) {
if(left!=NULL && right!=NULL && left->val == right->val) {
return isEqual(left->left, right->right) && isEqual(left->right, right->left);
}
return left==NULL && right==NULL;
}
};

解决方案2(Python)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
return self.isEqual(root.left, root.right)
def isEqual(self, left, right):
if left and right and left.val == right.val:
return self.isEqual(left.left, right.right) and self.isEqual(left.right, right.left)
return not left and not right

相关问题


题目来源