Oliver's Blog
Ctrlk
  • 🤩Welcome!
  • Projects
    • RISC Game
    • Mini Amazon
    • HTTP Caching Proxy
    • Course Enrollment App
    • Fitness Tracker App
    • Voice Shopping Assistant
    • Graphics Town
  • Algo
    • Binary Search
    • Linked List
    • Recursion Basics
    • Binary Tree
      • 1. Traversal
      • 2. Classical Questions
      • 3. Binary Search Tree
        • Insert Node in a Binary Search Tree
        • Remove Node in Binary Search Tree
        • Validate Binary Search Tree
        • Trim a Binary Search Tree
        • Search Range in Binary Search Tree
        • Inorder Successor in BST
        • Binary Search Tree Iterator
        • Recover Binary Search Tree
      • 4. Divide and Conquer
      • Convert Sorted Array to Binary Search Tree
      • Path Sum
      • Lowest Common Ancestor of a Binary Search Tree
      • Sum of Left Leaves
      • Minimum Absolute Difference in BST
      • Minimum Distance Between BST Nodes
      • Convert Sorted List to Binary Search Tree
      • Range Sum of BST
      • Kth Smallest Element in a BST
      • Find Largest Value in Each Tree Row
    • Sorting
    • Two Pointers
    • Queue & Stack
    • Hash Table
    • Heap & Priority Queue
    • BFS
    • Array
    • String
    • Math
    • Dynamic Programming
    • LeetCode vs. LintCode Table
  • React Notes
    • Optimizing Performance in React
  • Golang Notes
    • Basics
    • Official Tutorial Notes
  • Miscellaneous
    • Traveling to China During a Global Pandemic
Powered by GitBook
On this page
  1. Algo
  2. Binary Tree
  3. 3. Binary Search Tree

Trim a Binary Search Tree

ID: 701; medium; 修剪二叉搜索树

LogoLintCode 炼码 - 更高效的学习体验!www.lintcode.com
LogoTrim a Binary Search Tree - LeetCodeLeetCode

Solution 1 (Java)

PreviousValidate Binary Search TreeNextSearch Range in Binary Search Tree

Last updated 4 years ago

Was this helpful?

Was this helpful?

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