给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return helper(root,root);
}
public boolean helper(TreeNode root1,TreeNode root2){
if(root1==null&&root2==null){
return true;
}
if(root1==null||root2==null){
return false;
}
return root1.val==root2.val&&helper(root1.left,root2.right)&&helper(root1.right,root2.left);
}
}
本文介绍了一种检查二叉树是否为镜像对称的有效算法。通过对给定二叉树的节点进行递归比较,确保左子树是右子树的镜像,从而判断整个树是否对称。
1132

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



