669. Trim a Binary Search Tree

系统管理员 2024-04-08 09:26 184阅读 0赞

Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node’s descendant should remain a descendant). It can be proven that there is a unique answer.

Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.

Example 1:

03d59e898f3d5ea934b8b0fcd50d7de0.jpeg

  1. Input: root = [1,0,2], low = 1, high = 2
  2. Output: [1,null,2]

Example 2:

cbfd72ac1dc280ff39bd04b93baa4277.jpeg

  1. Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3
  2. Output: [3,2,null,1]

题目:给二叉搜索树剪枝,使得所有节点值都在[low, high]之间

思路:DFS。代码:

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12. class Solution {
  13. public:
  14. TreeNode* trimBST(TreeNode* root, int low, int high) {
  15. if(!root) return NULL;
  16. while(root && (root->val < low || root->val > high)){
  17. if(root->val < low) root = root->right;
  18. else root = root->left;
  19. }
  20. if(!root) return NULL;
  21. root->left = trimBST(root->left, low, high);
  22. root->right = trimBST(root->right, low, high);
  23. return root;
  24. }
  25. };

发表评论

表情:
评论列表 (有 0 条评论,184人围观)

还没有评论,来说两句吧...

相关阅读