Leetcode 669. Trim a Binary Search Tree
题目链接: Trim a Binary Search Tree
难度:Medium
题目大意:
将二叉树中节点值不在范围内的节点去除掉,保留二叉树的相对结构不变。
思路:
递归。
代码
/**
* 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) {
if(root==null){
return null;
}
if(root.val<low){
root=trimBST(root.right,low,high);
}
else if(root.val>high){
root=trimBST(root.left,low,high);
}
else{
root.left=trimBST(root.left,low,high);
root.right=trimBST(root.right,low,high);
}
return root;
}
}