From 5190b92cbbd58f76837d3b8cbe72790a02e76f2c Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Wed, 1 Feb 2023 10:45:58 +0800 Subject: [PATCH] s0235 --- ...st_common_ancestor_of_a_binary_search_tree.hpp | 11 +++++++++++ notes/src/SUMMARY.md | 1 + notes/src/bstree.md | 3 +++ ...st_common_ancestor_of_a_binary_search_tree.cpp | 15 +++++++++++++++ 4 files changed, 30 insertions(+) create mode 100644 include/s0235_lowest_common_ancestor_of_a_binary_search_tree.hpp create mode 100644 notes/src/bstree.md create mode 100644 src/s0235_lowest_common_ancestor_of_a_binary_search_tree.cpp 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; +}