This commit is contained in:
Sainnhe Park 2023-02-01 11:52:11 +08:00
parent a0517aa4d0
commit 968e8f3adc
3 changed files with 29 additions and 0 deletions

View File

@ -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

View File

@ -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 。递归修剪。

View File

@ -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);
}
}