【Lintcode】701. Trim a Binary Search Tree

Title address:

https://www.lintcode.com/problem/trim-a-binary-search-tree/description

Given a BST, then a range [ m i n , m a x ] [min, max] , request to delete all nodes in the tree that are not in this range, and return to the root of the deleted tree.

Can be solved by recursion, the code is as follows:

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 root;
        }
        // 如果树根小于下界,那么树根以及整个左子树都要被砍掉,只需返回右子树trim之后的结果就行;
        // 如果树根大于上界则也一样;否则分别将左右子树trim完接在树根上即可
        if (root.val < minimum) {
            return trimBST(root.right, minimum, maximum);
        } else if (root.val > maximum) {
            return trimBST(root.left, minimum, maximum);
        } else {
            root.left = trimBST(root.left, minimum, maximum);
            root.right = trimBST(root.right, minimum, maximum);
            return root;
        }
    }
}

class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int x) {
        val = x;
    }
}

time complexity THE ( n ) O (n) , space THE ( h ) O(h)

Published 387 original articles · liked 0 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/105450292