给定两颗二叉树,判断这两颗树在结构上是否相等。
示例如下:
贴出自己的实现
//对应节点
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 isSameTree(TreeNode tree1, TreeNode tree2) {
if (tree1 == null && tree2 == null) {
return true;
} else if (tree1 == null || tree2 == null) {
return false;
}
if (tree1 != null && tree2 != null) {
if (tree1.val != tree2.val) {
return false;
} else {
return isSameTree(tree1.left, tree2.left) && isSameTree(tree1.right, tree2.right);
}
}
}
给定一个二叉树,判断这颗二叉树是否为对称树
示例如下:
贴出自己的实现
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return isSymmetric(root.left, root.right);
}
//用于比较左右子树是否是镜像对称的
private boolean isSymmetric(TreeNode left, TreeNode right) {
if (left == null && right == null) {
return true;
} else if (left != null && right != null) {
if (left.val != right.val) {
return false;
} else {
return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
}
}
}
实现二
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return compare(root.left, root.right);
}
public boolean compare(TreeNode left, TreeNode right) {
if (left == null && right == null) {
return true;
}
if (left == null || right == null || left.val != right.val) {
return false;
}
return compare(left.left, right.right) && compare(right.left, left.right);
}