原题
请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的: 1
/ \
2 2
\ \
3 3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
- 直接比较
root->left
和root->right
- 再递归解决
root->left
的左子树和root->right
的右子树,root->left
的右子树和root->right
的左子树即可
代码
- C++代码
/**
* 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 {
private:
bool isSymmetric(TreeNode *&A, TreeNode *&B) {
if (A == nullptr && B == nullptr) {
return true;
}
if (A == nullptr) {
return false;
}
if (B == nullptr) {
return false;
}
if (A->val != B->val) {
return false;
}
return isSymmetric(A->left, B->right) && isSymmetric(A->right, B->left);
}
public:
bool isSymmetric(TreeNode* root) {
if (!root) {
return true;
}
return isSymmetric(root->left, root->right);
}
};
- Python代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def dfs(A, B):
# A,B同时遍历到最后,返回True
if not A and not B:
return True
# 只有A遍历到最后,返回False
if not A:
return False
# 只有B遍历到最后,返回False
if not B:
return False
# A.val 和 B.val不相等,返回False
if A.val != B.val:
return False
# 继续比较A.left, B.right和A.right, B.left
return dfs(A.left, B.right) and dfs(A.right, B.left)
if not root:
return True
# 判断root.left和root.right即可
return dfs(root.left, root.right)
时间复杂度 O ( N ) O(N) O(N) : N N N 为树节点数量,左子树和右子树是同时遍历的,即调用了 N 2 \frac{N}{2} 2N 次。
空间复杂度 O ( N ) O(N) O(N)