题目:修建二叉树,使得树中所有的结点值在区间[a,b]之间。
输入:
输出:
思路:关于二叉树的题,大部分都采用递归的方法来做。
- 当root为null时,直接返回null。
- 当root的值小于L,其左子树都小于L,故舍弃其左子树,递归的修剪其右子树,并返回修剪后的右子树。
- 当root的值大于L,其右子树都大于L,故舍弃其右子树,递归的修剪其左子树,并返回修剪后的左子树。
- 当root位于L和R之间时,递归的修剪其左右子树,并返回root。
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: given BST * @param minimum: the lower limit * @param maximum: the upper limit * @return: the root of the new tree */ public TreeNode trimBST(TreeNode root, int minimum, int maximum) { // write your code here if(root==null) return null; if(root.val<minimum) return trimBST(root.right,minimum,maximum); if(root.val>maximum) return trimBST(root.left,minimum,maximum); root.left=trimBST(root.left,minimum,maximum); root.right=trimBST(root.right,minimum,maximum); return root; } }