题目: 对称二叉树
题号:101
难易程度:简单
题面:
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。。
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
题目意思:
判断两个二叉树是对称的。
题解:
先判断是否为空,然后判左边的左子树和右边的右子树,左边的右子树和右边的左子树是否相等。
public class LeetCode101 {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return sameTree(root.left,root.right);
}
private static boolean sameTree(TreeNode l, TreeNode r) {
if (l == null && r == null) {
return true;
}
if (l == null || r == null || l.val != r.val) {
return false;
}
return sameTree(l.left, r.right) && sameTree(l.right, r.left);
}
}