leetcode 669. Trim a Binary Search Tree

水深无声 2022-06-09 11:12 288阅读 0赞

1.题目

Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.
修剪一棵二叉搜索树,使得所有节点的值都在[L,R]范围内

Example 1:
Input:

  1. 1
  2. / \
  3. 0 2

L = 1
R = 2

Output:

  1. 1
  2. \
  3. 2

Example 2:
Input:

  1. 3
  2. / \
  3. 0 4
  4. \
  5. 2
  6. /
  7. 1

L = 1
R = 3

Output:

  1. 3
  2. /
  3. 2
  4. /
  5. 1

2.分析

用递归来实现。从根结点开始,
如果节点值小于L,则砍掉左子树,只留右子树,对右子树进行修剪
如果节点值大于R,则砍掉右子树,只留左子树,对左子树进行修剪
如果节点值位于[L,R]范围内,则递归,分别对左右子树进行修剪

3.代码

  1. TreeNode* trimBST(TreeNode* root, int L, int R) {
  2. if (root == NULL)
  3. return root;
  4. if (root->val > R)
  5. return trimBST(root->left, L, R);
  6. else if (root->val < L)
  7. return trimBST(root->right, L, R);
  8. else {
  9. root->left = trimBST(root->left, L, R);
  10. root->right = trimBST(root->right, L, R);
  11. return root;
  12. }
  13. }

发表评论

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

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

相关阅读