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 1b9abdc

Browse files
committed
feat: update lcof solution: No.68
更新剑指Offer题解:面试题68 - II. 二叉树的最近公共祖先
1 parent 4ea9e02 commit 1b9abdc

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

‎lcof/面试题68 - II. 二叉树的最近公共祖先/README.md‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
例如,给定如下二叉树: root = `[3,5,1,6,2,0,8,null,null,7,4]`
1010

11-
![](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/15/binarytree.png)
11+
![](./images/binarytree.png)
1212

1313
**示例 1:**
1414

@@ -33,7 +33,19 @@
3333

3434
## 解法
3535
<!-- 这里可写通用的实现逻辑 -->
36-
递归求解。
36+
37+
根据"**最近公共祖先**"的定义,若 root 是 p, q 的最近公共祖先 ,则只可能为以下情况之一:
38+
39+
- 如果 p 和 q 分别是 root 的左右节点,那么 root 就是我们要找的最近公共祖先;
40+
- 如果 p 和 q 都是 root 的左节点,那么返回 `lowestCommonAncestor(root.left, p, q)`;
41+
- 如果 p 和 q 都是 root 的右节点,那么返回 `lowestCommonAncestor(root.right, p, q)`
42+
43+
**边界条件讨论**:
44+
45+
- 如果 root 为 null,则说明我们已经找到最底了,返回 null 表示没找到;
46+
- 如果 root 与 p 相等或者与 q 相等,则返回 root;
47+
- 如果左子树没找到,递归函数返回 null,证明 p 和 q 同在 root 的右侧,那么最终的公共祖先就是右子树找到的结点;
48+
- 如果右子树没找到,递归函数返回 null,证明 p 和 q 同在 root 的左侧,那么最终的公共祖先就是左子树找到的结点。
3749

3850
<!-- tabs:start -->
3951

7.35 KB
Loading[フレーム]

0 commit comments

Comments
(0)

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