s0235
This commit is contained in:
parent
2a188cde9d
commit
5190b92cbb
@ -0,0 +1,11 @@
|
|||||||
|
#ifndef S0235_LOWEST_COMMON_ANCESTOR_OF_A_BINARY_SEARCH_TREE_HPP
|
||||||
|
#define S0235_LOWEST_COMMON_ANCESTOR_OF_A_BINARY_SEARCH_TREE_HPP
|
||||||
|
|
||||||
|
#include "structures.hpp"
|
||||||
|
|
||||||
|
class S0235 {
|
||||||
|
public:
|
||||||
|
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q);
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif
|
@ -36,6 +36,7 @@
|
|||||||
|
|
||||||
- [理论基础](./btree_basic.md)
|
- [理论基础](./btree_basic.md)
|
||||||
- [遍历](./btree_iter.md)
|
- [遍历](./btree_iter.md)
|
||||||
|
- [二叉搜索树](./bstree.md)
|
||||||
|
|
||||||
# STL
|
# STL
|
||||||
|
|
||||||
|
3
notes/src/bstree.md
Normal file
3
notes/src/bstree.md
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
# 二叉搜索树
|
||||||
|
|
||||||
|
- [s0235](https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/description/): 找两个指定节点的最近公共祖先。思路很简单,只要出现分岔(即一个在当前节点的左边,一个在当前节点的右边),那么这个分岔点就是最近公共祖先。
|
15
src/s0235_lowest_common_ancestor_of_a_binary_search_tree.cpp
Normal file
15
src/s0235_lowest_common_ancestor_of_a_binary_search_tree.cpp
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
#include "s0235_lowest_common_ancestor_of_a_binary_search_tree.hpp"
|
||||||
|
|
||||||
|
TreeNode* S0235::lowestCommonAncestor(TreeNode* root, TreeNode* p,
|
||||||
|
TreeNode* q) {
|
||||||
|
TreeNode* result = root;
|
||||||
|
while (!((p->val <= result->val && q->val >= result->val) ||
|
||||||
|
(q->val <= result->val && p->val >= result->val))) {
|
||||||
|
if (p->val < result->val) {
|
||||||
|
result = result->left;
|
||||||
|
} else {
|
||||||
|
result = result->right;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user