Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9249286

Browse files
author
dai
committed
mirror symmetry tree
1 parent 2e38730 commit 9249286

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

‎26-算法面试专题-二叉树.md‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -594,6 +594,37 @@ public class TreeSolvingUtil {
594594
// 如果在右子树中,p和q都找不到,则 p和q一定都在左子树中,左子树中先遍历到的那个就是最近公共祖先(一个节点也可以是它自己的祖先)
595595
return left == null ? right : left;
596596
}
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+
597628

598629
}
599630
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /