Description
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.
Examples
Example 1:
Input: root = [1,0,2], low = 1, high = 2
Output: [1,null,2]
Example 2:
Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3
Output: [3,2,null,1]
Example 3:
Input: root = [1], low = 1, high = 2
Output: [1]
Example 4:
Input: root = [1,null,2], low = 1, high = 3
Output: [1,null,2]
Example 5:
Input: root = [1,null,2], low = 2, high = 4
Output: [2]
Constraints:
The number of nodes in the tree in the range [1, 104].
0 <= Node.val <= 1 0 4 10^4 104
The value of each node in the tree is unique.
root is guaranteed to be a valid binary search tree.
0 <= low <= high <= 1 0 4 10^4 104
思路
这题是删除所有不在规定区间内的二叉搜索树节点,并保留原格式
这道题虽然是删除操作,但也可以认为是构造过程,因此不用对当前节点的左右孩子做分别判断。
首先提一下二叉搜索树的默认规则:
- 左边永远小于右边
因此判断的时候
- 如果currNode.val < low
那么可能满足区间的节点一定出现在currNode.right中,所以逐步将currNode向右移直到找到这个节点或者到null为止 - 如果currNode.val > high
那么可能满足区间的节点一定出现在currNode.left中,所以逐步将currNode向左移直到找到这个节点或者到null为止
整个流程就可以变为:
- 首先找到第一个在区间内的节点作为根节点
- 对该节点的左右孩子分别找到在区间内的节点
说的可能不是很清楚,看代码比较简洁易懂
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
while (root != null && (root.val < low || root.val > high)){
if (root.val < low)
root = root.right;
else
root = root.left;
}
if(root == null)
return null;
root.right = trimBST(root.right, low, high);
root.left = trimBST(root.left, low, high);
return root;
}
}