修剪二叉搜索树
递归回溯剪切(代码复杂)
/** * Definition for a binary tree node. * 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) {} * }; */ class Solution { public: TreeNode* cut_tree(TreeNode* cur, int low, int high) { if(cur==nullptr) return cur; cur->left = cut_tree(cur->left , low , high); cur->right = cut_tree(cur->right , low , high); //当前值是边界值剪切 if(cur->val == low) cur->left = nullptr; else if(cur->val == high) cur->right = nullptr; //当前值超出边界值剪切 else if(cur->val < low) { TreeNode * tmp = cur; while(tmp->right != nullptr && tmp->right->val < low) { tmp = tmp->right; } if(tmp->right == nullptr) return nullptr; else return tmp->right; } else if(cur->val > high) { TreeNode * tmp = cur; while(tmp->left != nullptr && tmp->left->val > high) { tmp = tmp->left; } if(tmp->left == nullptr) return nullptr; else return tmp->left; } return cur; } TreeNode* trimBST(TreeNode* root, int low, int high) { return cut_tree(root,low,high); } };
递归回溯非剪切
/** * Definition for a binary tree node. * 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) {} * }; */ class Solution { public: TreeNode* cut_tree(TreeNode* cur, int low, int high) { if(cur==nullptr) return cur; if(cur->val < low) return cut_tree(cur->right,low,high); if(cur->val > high) return cut_tree(cur->left,low,high); cur->left = cut_tree(cur->left,low,high); cur->right = cut_tree(cur->right,low,high); return cur; } TreeNode* trimBST(TreeNode* root, int low, int high) { return cut_tree(root,low,high); } };
二刷
/** * Definition for a binary tree node. * 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) {} * }; */ class Solution { public: TreeNode* track_back(TreeNode* cur, int low, int high) { if(cur == nullptr ) return nullptr; if(cur->val < low ) { return track_back(cur->right , low , high); } else if(cur->val > high ) { return track_back(cur->left , low , high); } cur->left = track_back(cur->left , low , high); cur->right = track_back(cur->right , low , high); return cur; } TreeNode* trimBST(TreeNode* root, int low, int high) { return track_back(root,low,high); } };