669. Trim a Binary Search Tree

来源:互联网 发布:mac梦幻西游更新不了 编辑:程序博客网 时间:2024/06/06 04:02

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.

Example 1:

Input:     1   / \  0   2  L = 1  R = 2Output:     1      \       2

Example 2:

Input:     3   / \  0   4   \    2   /  1  L = 1  R = 3Output:       3     /    2     /

1

  • 当root的值位于LR之间,则递归修剪其左右子树,返回root。
  • 当root的值小于L,则其左子树的值都小于L,抛弃左子树,返回修剪过的右子树。
  • 当root的值大于R,则其右子树的值都大于R,抛弃右子树,返回修剪过的左子树。

 public static TreeNode TrimBST(TreeNode root, int L, int R)            {                if (root == null) return null;                if (root.val < L) return TrimBST(root.right, L, R);                if (root.val > R) return TrimBST(root.left, L, R);                root.left = TrimBST(root.left, L, R);                root.right = TrimBST(root.right, L, R);                return root;            }