1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Binary Search Trees Bst
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
09Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Binary Search Trees Bst

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
09Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

BST

Overview

A standard Binary Tree doesn't enforce any order, making search operations O(N). A Binary Search Tree (BST) imposes a strict mathematical rule on how nodes are arranged: 1. Every value in the left subtree must be less than the node's value. 2. Every value in the right subtree must be greater than the node's value.

This simple rule unlocks incredible performance. When searching for a value, you compare it to the root. If it's smaller, you completely eliminate the entire right half of the tree. If it's larger, you eliminate the left half. This halving process is identical to Binary Search in an array, resulting in O(log N) time complexity for Search, Insertion, and Deletion.

However, this O(log N) performance is only guaranteed if the tree is balanced. If you insert sorted data (e.g., 1, 2, 3, 4, 5) into a naive BST, it will form a straight line, degrading into a Linked List with O(N) performance.

Syntax

BST Insertion and Search
java
public class BST {
    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }
    
    TreeNode root;
    
    // O(log N) Insertion
    public void insert(int val) {
        root = insertRec(root, val);
    }
    
    private TreeNode insertRec(TreeNode root, int val) {
        // Base case: Found the empty spot!
        if (root == null) return new TreeNode(val);
        
        // Recursive routing based on BST rules
        if (val < root.val) {
            root.left = insertRec(root.left, val);
        } else if (val > root.val) {
            root.right = insertRec(root.right, val);
        }
        // If equal, do nothing (no duplicates allowed in this BST)
        return root;
    }
    
    // O(log N) Search
    public boolean search(int val) {
        TreeNode current = root;
        while (current != null) {
            if (current.val == val) return true; // Found it!
            
            // Choose the path
            if (val < current.val) current = current.left;
            else current = current.right;
        }
        return false; // Reached a leaf without finding it
    }
}

Common Pitfalls

  • Assuming a naive BST is always O(log N). In an interview, if you claim a BST search is O(log N), the interviewer will ask 'Always?'. The correct answer is: 'Only if it is balanced. The worst-case is O(N) if the tree becomes a degenerate linked list.'
  • Violating the BST property during complex modifications. Deleting a node with two children is notoriously tricky. You must find the 'Inorder Successor' (the smallest node in the right subtree), swap its value with the target node, and then delete the successor. If done incorrectly, the BST rules are permanently broken.
  • Checking only immediate children for BST validity. To validate if a tree is a BST, it's not enough to check left < root < right. A node deep in the left subtree might accidentally be larger than the absolute root. You must enforce MIN and MAX boundaries during traversal.

Interview Questions

How do you validate if a Binary Tree is a valid Binary Search Tree?

You use a recursive function that takes the node, a minimum valid value, and a maximum valid value. For the root, min is -Infinity and max is +Infinity. As you traverse left, you update the max limit to the current node's value. As you traverse right, you update the min limit. If any node violates its bounds, return false.

What is an AVL Tree or a Red-Black Tree?

They are 'Self-Balancing Binary Search Trees'. When nodes are inserted or deleted, these trees perform complex 'rotations' to ensure the tree never becomes degenerate (unbalanced). Java's TreeMap and TreeSet are internally implemented using Red-Black Trees to guarantee strict O(log N) performance.

Real-World Example

Database Indexing relies heavily on balanced search trees (usually B-Trees, a generalized form of BSTs). When you query a massive database (SELECT * WHERE id = 500), the database does not scan all 10 million rows. It traverses a B-Tree index, finding the exact disk location of ID 500 in a few milliseconds.

example
java
// Java's built-in self-balancing BST
import java.util.TreeMap;

public class DatabaseIndex {
    public static void main(String[] args) {
        // TreeMap guarantees O(log N) operations and keeps keys sorted
        TreeMap<Integer, String> index = new TreeMap<>();
        
        index.put(500, "Disk_Sector_A12");
        index.put(100, "Disk_Sector_B04");
        index.put(900, "Disk_Sector_Z99");
        
        // Finding an item is blazing fast, even with millions of keys
        String diskLocation = index.get(500); 
    }
}

Check Your Knowledge

Test your understanding of BST with these quick questions.

Question 1

What rule must every node in a Binary Search Tree obey?

Question 2

What happens if you insert already sorted data (1, 2, 3, 4, 5) into a standard, non-balancing BST?

Question 3

Which Java collection uses a Red-Black Tree (a balanced BST) internally?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

BST

Overview

A standard Binary Tree doesn't enforce any order, making search operations O(N). A Binary Search Tree (BST) imposes a strict mathematical rule on how nodes are arranged: 1. Every value in the left subtree must be less than the node's value. 2. Every value in the right subtree must be greater than the node's value.

This simple rule unlocks incredible performance. When searching for a value, you compare it to the root. If it's smaller, you completely eliminate the entire right half of the tree. If it's larger, you eliminate the left half. This halving process is identical to Binary Search in an array, resulting in O(log N) time complexity for Search, Insertion, and Deletion.

However, this O(log N) performance is only guaranteed if the tree is balanced. If you insert sorted data (e.g., 1, 2, 3, 4, 5) into a naive BST, it will form a straight line, degrading into a Linked List with O(N) performance.

Syntax

BST Insertion and Search
java
public class BST {
    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }
    
    TreeNode root;
    
    // O(log N) Insertion
    public void insert(int val) {
        root = insertRec(root, val);
    }
    
    private TreeNode insertRec(TreeNode root, int val) {
        // Base case: Found the empty spot!
        if (root == null) return new TreeNode(val);
        
        // Recursive routing based on BST rules
        if (val < root.val) {
            root.left = insertRec(root.left, val);
        } else if (val > root.val) {
            root.right = insertRec(root.right, val);
        }
        // If equal, do nothing (no duplicates allowed in this BST)
        return root;
    }
    
    // O(log N) Search
    public boolean search(int val) {
        TreeNode current = root;
        while (current != null) {
            if (current.val == val) return true; // Found it!
            
            // Choose the path
            if (val < current.val) current = current.left;
            else current = current.right;
        }
        return false; // Reached a leaf without finding it
    }
}

Common Pitfalls

  • Assuming a naive BST is always O(log N). In an interview, if you claim a BST search is O(log N), the interviewer will ask 'Always?'. The correct answer is: 'Only if it is balanced. The worst-case is O(N) if the tree becomes a degenerate linked list.'
  • Violating the BST property during complex modifications. Deleting a node with two children is notoriously tricky. You must find the 'Inorder Successor' (the smallest node in the right subtree), swap its value with the target node, and then delete the successor. If done incorrectly, the BST rules are permanently broken.
  • Checking only immediate children for BST validity. To validate if a tree is a BST, it's not enough to check left < root < right. A node deep in the left subtree might accidentally be larger than the absolute root. You must enforce MIN and MAX boundaries during traversal.

Interview Questions

How do you validate if a Binary Tree is a valid Binary Search Tree?

You use a recursive function that takes the node, a minimum valid value, and a maximum valid value. For the root, min is -Infinity and max is +Infinity. As you traverse left, you update the max limit to the current node's value. As you traverse right, you update the min limit. If any node violates its bounds, return false.

What is an AVL Tree or a Red-Black Tree?

They are 'Self-Balancing Binary Search Trees'. When nodes are inserted or deleted, these trees perform complex 'rotations' to ensure the tree never becomes degenerate (unbalanced). Java's TreeMap and TreeSet are internally implemented using Red-Black Trees to guarantee strict O(log N) performance.

Real-World Example

Database Indexing relies heavily on balanced search trees (usually B-Trees, a generalized form of BSTs). When you query a massive database (SELECT * WHERE id = 500), the database does not scan all 10 million rows. It traverses a B-Tree index, finding the exact disk location of ID 500 in a few milliseconds.

example
java
// Java's built-in self-balancing BST
import java.util.TreeMap;

public class DatabaseIndex {
    public static void main(String[] args) {
        // TreeMap guarantees O(log N) operations and keeps keys sorted
        TreeMap<Integer, String> index = new TreeMap<>();
        
        index.put(500, "Disk_Sector_A12");
        index.put(100, "Disk_Sector_B04");
        index.put(900, "Disk_Sector_Z99");
        
        // Finding an item is blazing fast, even with millions of keys
        String diskLocation = index.get(500); 
    }
}

Check Your Knowledge

Test your understanding of BST with these quick questions.

Question 1

What rule must every node in a Binary Search Tree obey?

Question 2

What happens if you insert already sorted data (1, 2, 3, 4, 5) into a standard, non-balancing BST?

Question 3

Which Java collection uses a Red-Black Tree (a balanced BST) internally?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A