面试题28:对称的二叉树
题目:请实现一个函数,用来判断一颗二叉树是不是对称的。如果一颗二叉树和它的镜像一样,那么它是对称的。如下图所示的二叉树就是对称的。
思路:
- 前序遍历:中左右 8657675
- 对称前序遍历:中右左 8657675
- 同时进行前序遍历和对称前序遍历,如果遍历结束全部相等则是对称二叉树,否则不是
代码实现:
package Question28;
public class T01 {
public static void main(String[] args) {
Node node8 = new Node(8);
Node node6_1 = new Node(6);
Node node6_2 = new Node(6);
Node node5_1 = new Node(5);
Node node5_2 = new Node(5);
Node node7_1 = new Node(7);
Node node7_2 = new Node(7);
node8.left = node6_1;
node8.right = node6_2;
node6_1.left = node5_1;
node6_1.right = node7_1;
node6_2.left = node7_2;
node6_2.right = node5_2;
System.out.println(solve(node8, node8));
}
public static boolean solve(Node root1, Node root2) {
if(root1 == null && root2 == null) return true;
if(root1 == null || root2 == null) return false;
if(root1.val != root2.val) return false;
return solve(root1.left, root2.right) && solve(root1.right, root2.left);
}
}
class Node {
int val;
Node left;
Node right;
public Node(int val) {
this.val = val;
}
}