Trim a Binary Search Tree
Description:
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 = 2
Output:
1
\
2
Example 2:
Input:
3
/ \
0 4
\
2
/
1
L = 1
R = 3
Output:
3
/
2
/
1
问题描述:
给定一个二叉搜索树,以及两个边界L,R。修剪这个树,使这个树中所有的节点值在[L,R]中。
Solution:
这个题没什么好说的,就是一定要审题,这是一个二叉搜索树!!!
二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。
根据其性质,并且采取同步更新策略。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode trimBST(TreeNode root, int L, int R) {
if(root == null) return null;
root.left = trimBST(root.left, L, R);
root.right = trimBST(root.right, L, R);
return (root.val > R)? root.left : ((root.val < L)? root.right : root);
}
}