版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/88988566
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
题意:要求对一颗BST树进行剪枝操作,使得所有节点的值都在[L, R](L <= R)范围内;返回剪枝后的BST树;
解法:对于一颗BST树有如下三个特点
- root.val > root.left.val
- root.val < root.right.val
- 当我们对BST树利用中序遍历时可以得到一个升序排序的序列;
利用这三个特点,我们对每个节点root,进行如下判断
- if root.val < L:则满足条件的节点必然在root.right部分
- if root.val > R: 则满足条件的节点必然在root.left部分
- 否则,root是我们所要找的节点
Java
/**
* 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 root;
}
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;
}
}