Trim a Binary Search Tree

https://leetcode.com/problems/trim-a-binary-search-tree/discuss/

Given a binary search tree and the lowest and highest boundaries asLandR, trim the tree so that all its elements lies in[L, R](R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.

Thoughts

用经典的分治解法即可。假设左右子树都已完成剪枝,对当前root节点的处理要用到二叉搜索树的性质。

Code

/**
 * 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;
        }

        root.left = trimBST(root.left, L, R);
        root.right = trimBST(root.right, L, R);
        if (root.val < L) {
            return root.right;
        } else if (root.val > R) {
            return root.left;
        } else {
            return root;
        }
    }
}

Analysis

时间复杂度为所有树节点树。还可以做一些小优化,比如把对root判断条件放到前面从而减少需要检查的节点。

Last updated