Skip to content

Commit 9262be6

Browse files
ChunelFengjunfeng.fj
and
junfeng.fj
authored
更新了[lcof-68.2 二叉树的最近公共祖先] (#348)
* 增加了[lcof-18.删除链表的节点]和[lcof-40.最小的k个数]的cpp解法,基本双优 * 优化[lcof-40.最小的k个数]格式 * 更新了[lcof-57.和为s的连续正整数序列]的cpp版本解法 * 更新了[lcof-68.2 二叉树的最近公共祖先] Co-authored-by: junfeng.fj <junfeng.fj@alibaba-inc.com>
1 parent 3aa1b9e commit 9262be6

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

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

+38
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,44 @@ var lowestCommonAncestor = function (root, p, q) {
129129
};
130130
```
131131

132+
### **C++**
133+
134+
```cpp
135+
/**
136+
* Definition for a binary tree node.
137+
* struct TreeNode {
138+
* int val;
139+
* TreeNode *left;
140+
* TreeNode *right;
141+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
142+
* };
143+
*/
144+
145+
class Solution {
146+
public:
147+
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
148+
// 如果找到val,层层向上传递该root
149+
if (nullptr == root || p->val == root->val || q->val == root->val) {
150+
return root;
151+
}
152+
153+
TreeNode* left = lowestCommonAncestor(root->left, p, q);
154+
TreeNode* right = lowestCommonAncestor(root->right, p, q);
155+
156+
if (left != nullptr && right != nullptr) {
157+
// 如果两边都可以找到
158+
return root;
159+
} else if (left == nullptr) {
160+
// 如果左边没有找到,则直接返回右边内容
161+
return right;
162+
} else {
163+
return left;
164+
}
165+
}
166+
};
167+
168+
```
169+
132170
### **...**
133171

134172
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
11+
class Solution {
12+
public:
13+
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
14+
// 如果找到val,层层向上传递该root
15+
if (nullptr == root || p->val == root->val || q->val == root->val) {
16+
return root;
17+
}
18+
19+
TreeNode* left = lowestCommonAncestor(root->left, p, q);
20+
TreeNode* right = lowestCommonAncestor(root->right, p, q);
21+
22+
if (left != nullptr && right != nullptr) {
23+
// 如果两边都可以找到
24+
return root;
25+
} else if (left == nullptr) {
26+
// 如果左边没有找到,则直接返回右边内容
27+
return right;
28+
} else {
29+
return left;
30+
}
31+
}
32+
};

0 commit comments

Comments
 (0)