首页 > 试题广场 >

算法题,trim二叉搜索树

[问答题]

算法题,trim二叉搜索树

/**
 * 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) {
        return dfs(root, L, R);
    }
    
    public TreeNode dfs(TreeNode root, int L, int R) {
        if (root == null) return root;
        if (root.val > R) return dfs(root.left, L, R);
        if (root.val < L) return dfs(root.right, L, R);
        
        root.left = dfs(root.left, L, R);
        root.right = dfs(root.right, L, R);
        return root;
    }
}
发表于 2019-06-28 13:06:52 回复(0)