We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 2e38730 commit 9249286Copy full SHA for 9249286
26-算法面试专题-二叉树.md
@@ -594,6 +594,37 @@ public class TreeSolvingUtil {
594
// 如果在右子树中,p和q都找不到,则 p和q一定都在左子树中,左子树中先遍历到的那个就是最近公共祖先(一个节点也可以是它自己的祖先)
595
return left == null ? right : left;
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
628
629
630
```
AltStyle によって変換されたページ (->オリジナル) / アドレス: モード: デフォルト 音声ブラウザ ルビ付き 配色反転 文字拡大 モバイル
0 commit comments