
审题:
二叉搜索树:又称二叉排序树,其左子树的值<根节点<右子树
思路:
若根节点>R,则考虑其左子树
若根节点<L,则考虑其右子树
以此类推
代码:
/**
- 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; } if(root.val>R){ return trimBST(root.left,L,R); } if(root.val<L){ return trimBST(root.right,L,R); } root.left = trimBST(root.left,L,R); root.right = trimBST(root.right,L,R); return root;}
}




近期评论