From 968e8f3adc84913c86b844fa16cbc5e427d1603d Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Wed, 1 Feb 2023 11:52:11 +0800 Subject: [PATCH] s0669 --- include/s0669_trim_a_binary_search_tree.hpp | 11 +++++++++++ notes/src/bstree.md | 1 + src/s0669_trim_a_binary_search_tree.cpp | 17 +++++++++++++++++ 3 files changed, 29 insertions(+) create mode 100644 include/s0669_trim_a_binary_search_tree.hpp create mode 100644 src/s0669_trim_a_binary_search_tree.cpp diff --git a/include/s0669_trim_a_binary_search_tree.hpp b/include/s0669_trim_a_binary_search_tree.hpp new file mode 100644 index 0000000..e8eccff --- /dev/null +++ b/include/s0669_trim_a_binary_search_tree.hpp @@ -0,0 +1,11 @@ +#ifndef S0669_TRIM_A_BINARY_SEARCH_TREE_HPP +#define S0669_TRIM_A_BINARY_SEARCH_TREE_HPP + +#include "structures.hpp" + +class S0669 { + public: + TreeNode* trimBST(TreeNode* root, int low, int high); +}; + +#endif diff --git a/notes/src/bstree.md b/notes/src/bstree.md index dc24e74..272308c 100644 --- a/notes/src/bstree.md +++ b/notes/src/bstree.md @@ -3,3 +3,4 @@ - [s0235](https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/description/): 找两个指定节点的最近公共祖先。思路很简单,只要出现分岔(即一个在当前节点的左边,一个在当前节点的右边),那么这个分岔点就是最近公共祖先。 - [s0701](https://leetcode.cn/problems/insert-into-a-binary-search-tree/description/): 插入节点。一层一层往下找,直到发现找不到了就在这个地方插入。 - [s0450](https://leetcode.cn/problems/delete-node-in-a-bst/description/): 删除节点。递归删除。 +- [s0669](https://leetcode.cn/problems/trim-a-binary-search-tree/description/): 修剪 BST 。递归修剪。 diff --git a/src/s0669_trim_a_binary_search_tree.cpp b/src/s0669_trim_a_binary_search_tree.cpp new file mode 100644 index 0000000..9d3fc79 --- /dev/null +++ b/src/s0669_trim_a_binary_search_tree.cpp @@ -0,0 +1,17 @@ +#include "s0669_trim_a_binary_search_tree.hpp" + +TreeNode* S0669::trimBST(TreeNode* root, int low, int high) { + if (root == nullptr) return nullptr; + if (low <= root->val && root->val <= high) { + // 如果根节点的值位于范围内,则对左右子树进行剪裁 + root->left = trimBST(root->left, low, high); + root->right = trimBST(root->right, low, high); + return root; + } else if (root->val < low) { + // 如果根节点的值小于 low, 把根节点和左子树都剪裁掉 + return trimBST(root->right, low, high); + } else { + // 如果根节点的值大于 high, 把根节点和右子树都剪裁掉 + return trimBST(root->left, low, high); + } +}