File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change @@ -594,6 +594,37 @@ public class TreeSolvingUtil {
594
594
// 如果在右子树中,p和q都找不到,则 p和q一定都在左子树中,左子树中先遍历到的那个就是最近公共祖先(一个节点也可以是它自己的祖先)
595
595
return left == null ? right : left;
596
596
}
597
+
598
+
599
+ /**
600
+ * 8、给定一个二叉树头节点,判断这颗树是否是镜面堆成的。即是否是是镜像二叉树
601
+ *
602
+ */
603
+ public boolean isSymmetric (TreeNode root ) {
604
+ // 自身,和自身的镜像树去递归比较
605
+ return isMirror(root, root);
606
+ }
607
+
608
+ // 一棵树是原始树 head1
609
+ // 另一棵是翻面树 head2
610
+ public static boolean isMirror (TreeNode head1 , TreeNode head2 ) {
611
+ // base case 当前镜像的节点都为空,也算合法的镜像
612
+ if (head1 == null && head2 == null ) {
613
+ return true ;
614
+ }
615
+ // 互为镜像的两个点不为空
616
+ if (head1 != null && head2 != null ) {
617
+ // 当前两个镜像点要是相等的,
618
+ // A树的左树和B树的右树互为镜像且满足,且A树的右树和B树的左树互为镜像,且满足。
619
+ // 那么当前的镜像点下面的都是满足的
620
+ return head1. val == head2. val
621
+ && isMirror(head1. left, head2. right)
622
+ && isMirror(head1. right, head2. left);
623
+ }
624
+ // 一个为空,一个不为空 肯定不构成镜像 false
625
+ return false ;
626
+ }
627
+
597
628
598
629
}
599
630
```
You can’t perform that action at this time.
0 commit comments