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.
Analysis:
recursion
situations that left child is same with right child
left.val == right.val or left == right == null
left.left child == right.right child
left.right child == right.left child
java
public boolean isSymmetric(TreeNode root) {
if(root==null) return true;
return symmetric(root.left, root.right);
}
public boolean symmetric(TreeNode left, TreeNode right){
if(left == null) return right==null;
if(right == null) return left==null;
if(left.val!=right.val) return false;
if(!symmetric(left.left, right.right)) return false;
if(!symmetric(left.right, right.left)) return false;
return true;
}
c++
bool isSymmetric(TreeNode *root) {
if(root == NULL) return true;
return symmetric(root->left,root->right);
}
bool symmetric(TreeNode *left, TreeNode *right){
if(left == NULL) return right==NULL;
if(right == NULL) return left==NULL;
if(left->val!=right->val) return false;
if(!symmetric(left->left,right->right)) return false;
if(!symmetric(left->right,right->left)) return false;
return true;
}

本文介绍了一种检查二叉树是否为中心对称的方法,提供了递归和迭代两种解决方案,并详细解释了每一步的判断逻辑。通过示例对比帮助理解二叉树对称性的概念。
177

被折叠的 条评论
为什么被折叠?



