diff --git a/include/s0235_lowest_common_ancestor_of_a_binary_search_tree.hpp b/include/s0235_lowest_common_ancestor_of_a_binary_search_tree.hpp new file mode 100644 index 0000000..341f20e --- /dev/null +++ b/include/s0235_lowest_common_ancestor_of_a_binary_search_tree.hpp @@ -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 diff --git a/notes/src/SUMMARY.md b/notes/src/SUMMARY.md index aa81aa1..fb41751 100644 --- a/notes/src/SUMMARY.md +++ b/notes/src/SUMMARY.md @@ -36,6 +36,7 @@ - [理论基础](./btree_basic.md) - [遍历](./btree_iter.md) +- [二叉搜索树](./bstree.md) # STL diff --git a/notes/src/bstree.md b/notes/src/bstree.md new file mode 100644 index 0000000..1bb9703 --- /dev/null +++ b/notes/src/bstree.md @@ -0,0 +1,3 @@ +# 二叉搜索树 + +- [s0235](https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/description/): 找两个指定节点的最近公共祖先。思路很简单,只要出现分岔(即一个在当前节点的左边,一个在当前节点的右边),那么这个分岔点就是最近公共祖先。 diff --git a/src/s0235_lowest_common_ancestor_of_a_binary_search_tree.cpp b/src/s0235_lowest_common_ancestor_of_a_binary_search_tree.cpp new file mode 100644 index 0000000..91b5beb --- /dev/null +++ b/src/s0235_lowest_common_ancestor_of_a_binary_search_tree.cpp @@ -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; +}