算法内容
本文件实现 LeetCode 669「修剪二叉搜索树」。目标是删除 BST 中所有不在 [low, high] 范围内的节点,并保持剩余结构仍为二叉搜索树。
代码利用 BST 性质:如果当前根值大于 high,合法节点只可能在左子树;如果当前根值小于 low,合法节点只可能在右子树。find(TreeNode** root) 通过二级指针直接修改父节点指向,先把当前根调整到合法范围,再递归修剪左右子树。每个节点最多访问一次,时间复杂度 O(n),递归空间复杂度 O(h)。
算法实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} };
#include<vector> #include<iostream> #include<stack> #include<queue> #include<algorithm> #include<unordered_map>
using namespace std;
class Solution { public: int low, high; TreeNode* trimBST(TreeNode* root, int low, int high) { this->low = low; this->high = high; find(&root); return root; }
bool valid(const int& i) { return i>= low && i <= high; }
void find(TreeNode** root) { while((*root) != nullptr && !valid((*root)->val)){ if((*root)->val > high) { *root = (*root)->left; } else if((*root)->val < low) { *root = (*root)->right; } } if((*root) == nullptr) return; if((*root)->left != nullptr) { find(&((*root)->left)); } if((*root)->right != nullptr) { find(&((*root)->right)); } } };
|