Open youngyangyang04 opened 3 months ago
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
return compare(root.left, root.right);
}
private boolean compare(TreeNode left, TreeNode right) {
if(left == null && right == null){
return true;
} else if(left != null && right == null){
return false;
} else if(left == null && right != null){
return false;
} else if(left.val != right.val){
return false;
}
boolean outside = compare(left.left, right.right);
boolean inside = compare(left.right, right.left);
return outside && inside;
}
}
就简简单单的递归罢了:
class Solution { public boolean isSymmetric(TreeNode root) { if(root==null)return true; return isMirror(root.left,root.right); }
private boolean isMirror(TreeNode left,TreeNode right){ if(left==null&&right==null)return true; else if(left==null||right==null)return false; return (left.val==right.val)&&isMirror(left.left,right.right)&&isMirror(left.right,right.left); } }
我怎么看到一个二叉树就想用层序遍历做。。
https://www.programmercarl.com/0101.%E5%AF%B9%E7%A7%B0%E4%BA%8C%E5%8F%89%E6%A0%91.html