Last updated on 2023年7月26日 中午
669. 修剪二叉搜索树(递归实现,C++)
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
|
class Solution { public: TreeNode* trimBST(TreeNode* root, int low, int high) { if(root == NULL){ return NULL; }
if(root->val < low){ TreeNode* node = trimBST(root->right, low, high); return node; }
if(root->val > high){ TreeNode* node = trimBST(root->left, low, high); return node; }
root->left = trimBST(root->left, low, high); root->right = trimBST(root->right, low, high); return root; } };
|
669. 修剪二叉搜索树(迭代法实现,C++)
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 51
|
class Solution { public: TreeNode* trimBST(TreeNode* root, int low, int high) { if(root == NULL){ return NULL; }
while(root != NULL && (root->val < low || root->val > high)){ if(root->val < low){ root = root->right; }else{ root = root->left; } }
TreeNode* curr = root; while(curr != NULL){ while(curr->left != NULL && curr->left->val < low){ curr->left = curr->left->right; } curr = curr->left; }
curr = root;
while(curr != NULL){ while(curr->right != NULL && curr->right->val > high){ curr->right = curr->right->left; } curr = curr->right; }
return root; } };
|
my-leetcode-logs-20230719
https://thewangyang.github.io/2023/07/19/leetcode-notes-20230719/