面试题28:对称的二叉树
题目:请实现一个函数,用来判断一颗二叉树是不是对称的。如果一颗二叉树和它的镜像一样,那么他是对称的
思路:
用两棵树的前向遍历顺序来判断,如果对称,则原来的树与镜像树的前向遍历顺序应相同
迭代比较
public class Q28 {
public static void main(String[] args) {
BinaryTreeNode myTree1 = myTree1();
BinaryTreeNode myTree2 = myTree1();
mirror(myTree1);
System.out.println("mirror-tree1:");
printTree(myTree1);
System.out.println("\ntree2:");
printTree(myTree2);
System.out.println();
System.out.println(campTree(myTree1,myTree2));
}
// 镜像
public static void mirror(BinaryTreeNode root) {
if(root!=null) {
BinaryTreeNode temp = root.leftNode;
root.leftNode = root.rightNode;
root.rightNode = temp;
if(root.leftNode!=null) {
mirror(root.leftNode);
}
if(root.rightNode!=null) {
mirror(root.rightNode);
}
}
}
// 先序比较
public static boolean campTree(BinaryTreeNode root1,BinaryTreeNode root2) {
boolean result = true;
result = (root1.val-root2.val<0.000001 && root2.val-root1.val<0.000001 );
if(result==false) {
return result;
}
if(root1.leftNode!=null && root2.leftNode!=null) {
result = campTree(root1.leftNode,root2.leftNode);
}else {
if(root1.leftNode!=null || root2.leftNode!=null)
return false;
}
if(result==true) {
if(root1.rightNode!=null && root2.rightNode!=null) {
result = campTree(root1.rightNode,root2.rightNode);
}else {
if(root1.rightNode!=null || root2.rightNode!=null)
return false;
}
}
return result;
}
public static BinaryTreeNode myTree1() {
BinaryTreeNode root = new BinaryTreeNode(8);
BinaryTreeNode node8 = new BinaryTreeNode(7);
BinaryTreeNode node7 = new BinaryTreeNode(7);
BinaryTreeNode node9 = new BinaryTreeNode(9);
node8.leftNode = node9;
BinaryTreeNode node2 = new BinaryTreeNode(2);
node8.rightNode = node2;
BinaryTreeNode node4 = new BinaryTreeNode(4);
node2.leftNode = node4;
BinaryTreeNode node2_7 = new BinaryTreeNode(7);
node2.rightNode = node2_7;
root.leftNode = node8;
root.rightNode = node7;
return root;
}
// 先序打印
public static void printTree(BinaryTreeNode root) {
System.out.printf("%f ", root.val);
if(root.leftNode!=null) {
printTree(root.leftNode);
}
if(root.rightNode!=null) {
printTree(root.rightNode);
}
}
}