在做剑指中对称二叉树这一道题目时,我的思路时先把二叉树的镜像转换出来,在把两棵二叉树的左子树和右子树分别进行比较。(更简便的应该是直接将二叉树的左子树与右子树进行比较,而不必转换,不过当时没想到),不过重点不在这,先看最初的代码
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
public int getVal() {
return val;
}
}
public class BinaryTree {
public static void main(String args[]) {
TreeNode root = new TreeNode(8);
root.left = new TreeNode(6);
root.left.left = new TreeNode(5);
root.left.right = new TreeNode(7);
root.right = new TreeNode(6);
root.right.left = new TreeNode(7);
root.right.right = new TreeNode(5);
boolean flag = isSymmetrical(root);
System.out.println(flag);
}
public static boolean isSymmetrical(TreeNode pRoot)
{
TreeNode root = pRoot;
Mirror(root);
return check(pRoot,root);
}
public static boolean check(TreeNode pRoot,TreeNode root){
if(pRoot == null && root == null){
return true;
}
if(pRoot.val != root.val){
return false;
}else{
return check(pRoot.left,root.left) && check(pRoot.right,root.right);
}
}
public static void Mirror(TreeNode root){
if(root == null){
return;
}
if(root.left == null && root.right == null){
return;
}
TreeNode node = root.left;
root.left = root.right;
root.right = node;
Mirror(root.left);
Mirror(root.right);
}
}
这个思路是没有什么问题的,但是我忽视了
TreeNode root = pRoot;
这两个对象指向的还是同一片内存,当我转换成镜像时,pRoot也变化了,所以两棵二叉树比较一直是true
在这里一定要使用深拷贝,
1.实现Cloneable接口
2.重写clone方法
!!3.TreeNode中的left,right这两个引用,也需要进行clone,将左右节点进行拷贝,否则从某种意义上,也只是浅拷贝。
class TreeNode implements Cloneable{
---
public Object clone(){
TreeNode o = null;
try {
o = (TreeNode) super.clone();
//二叉树中左右节点可能为空,所有需要判断一下
if(left!= null) {
//将类中的引用进行拷贝
o.left = (TreeNode) left.clone();
}
if(right!=null) {
o.right = (TreeNode) right.clone();
}
} catch (CloneNotSupportedException e) {
System.out.println(e.toString());
}
return o;
}
}