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

Appearance settings

Commit a81a67f

Browse filesBrowse files
author
dai
committed
tree commit
1 parent 96ba7bb commit a81a67f
Copy full SHA for a81a67f

File tree

Expand file treeCollapse file tree

1 file changed

+31
-4
lines changed
Open diff view settings
Filter options
Expand file treeCollapse file tree

1 file changed

+31
-4
lines changed
Open diff view settings
Collapse file

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

Copy file name to clipboardExpand all lines: 26-算法面试专题-二叉树.md
+31-4Lines changed: 31 additions & 4 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -561,12 +561,39 @@ public class TreeSolvingUtil {
561561
System.out.println();
562562
}
563563

564-
/**
565-
* 6、二叉树zigzag打印
566-
*/
567-
568564
/**
569565
* 7、二叉树,给定量给节点,求这两个节点的最近公共祖先
566+
*
567+
* @param root 根节点
568+
* @param p p节点
569+
* @param q q节点
570+
* @return
570571
*/
572+
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
573+
574+
// 如果树为空,直接返回null;
575+
// 如果 p和q中有等于 root的,那么它们的最近公共祖先即为root(一个节点也可以是它自己的祖先)
576+
if (root == null || p == root || q == root) {
577+
return root;
578+
}
579+
580+
581+
// 递归遍历左子树,只要在左子树中找到了p或q,则先找到谁就返回谁
582+
TreeNode left = lowestCommonAncestor(root.left, p, q);
583+
// 递归遍历右子树,只要在右子树中找到了p或q,则先找到谁就返回谁
584+
TreeNode right = lowestCommonAncestor(root.right, p, q);
585+
586+
587+
// left和 right均不为空时,说明 p、q节点分别在 root异侧, 最近公共祖先即为 root
588+
if (left != null && right != null) {
589+
return root;
590+
}
591+
592+
// 如果在左子树中p和q都找不到,则p和q一定都在右子树中,右子树中先遍历到的那个就是最近公共祖先(一个节点也可以是它自己的祖先)
593+
// 否则,如果 left不为空,在左子树中有找到节点(p或q),这时候要再判断一下右子树中的情况,
594+
// 如果在右子树中,p和q都找不到,则 p和q一定都在左子树中,左子树中先遍历到的那个就是最近公共祖先(一个节点也可以是它自己的祖先)
595+
return left == null ? right : left;
596+
}
597+
571598
}
572599
```

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.