1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Binary Trees
45% OFFBLACK FRIDAY SALE
Sale ends in
02Days
13Hrs
13Mins
36Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Binary Trees

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

02Days
13Hrs
13Mins
36Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
    • Java + DSA
    • Full Stack Web Dev
    • AI/ML + Python
  • 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

Binary Trees

Overview

A Binary Tree is a hierarchical data structure where every node has at most two children, referred to as the left child and the right child.

Unlike linear data structures (arrays, linked lists) where data is traversed sequentially, trees allow for branching. The top node is the root, and nodes with no children are leaves. Trees inherently represent hierarchical data: file systems, company org charts, XML/HTML document object models (DOM), and routing protocols all rely on tree structures.

The true power of a Binary Tree lies in its recursive nature. Every child node is itself the root of a smaller 'subtree'. This means nearly every operation on a binary tree (searching, traversing, calculating height) can be elegantly solved using a few lines of recursive code. However, a pure Binary Tree has no ordering rules regarding where data is placed, meaning searching for a specific value still requires checking every node (O(N) time).

Syntax

Defining and Building a Binary Tree
java
public class BinaryTree {
    // Standard Binary Tree Node
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        
        TreeNode(int val) {
            this.val = val;
        }
    }
    
    public static void main(String[] args) {
        // Constructing a small tree manually
        //       1
        //      /         //     2   3
        //    /
        //   4
        
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        
        // Calculating height recursively
        System.out.println("Tree Height: " + getHeight(root)); // Output: 3
    }
    
    // The beauty of trees: Recursive logic is trivial
    public static int getHeight(TreeNode node) {
        if (node == null) return 0; // Base case
        
        int leftHeight = getHeight(node.left);
        int rightHeight = getHeight(node.right);
        
        return Math.max(leftHeight, rightHeight) + 1;
    }
}

Common Pitfalls

  • NullPointerExceptions during traversal. Before accessing node.left or node.right, you must always ensure node != null. The base case of almost every recursive tree algorithm should be if (node == null) return ...;.
  • StackOverflowError on deeply unbalanced trees. If a tree heavily leans to one side (essentially becoming a linked list), recursive algorithms will push O(N) frames onto the call stack. For a tree with 50,000 nodes, this will crash the JVM. In production, highly unbalanced trees often require iterative solutions or self-balancing structures.
  • Losing track of the root node. In many tree modifications, if you reassign the root reference locally without returning or updating the global structure, you'll lose the tree entirely.

Interview Questions

What is the difference between a Full Binary Tree and a Complete Binary Tree?

In a Full Binary Tree, every node has exactly 0 or 2 children (no node has only 1 child). In a Complete Binary Tree, every level is completely filled except possibly the last level, and all nodes in the last level are as far left as possible. Complete Binary Trees are the foundation of Heaps.

Why do we use recursion so heavily with trees?

Because trees are inherently recursive data structures. A tree consists of a root node and two subtrees, which are themselves trees. Therefore, solving a problem for a single node and recursively delegating the same problem to its children naturally traverses the entire structure with minimal code.

Real-World Example

The HTML DOM (Document Object Model) that renders every web page is a tree structure (though generally an N-ary tree, not strictly binary). When JavaScript executes document.getElementById(), the browser performs a tree traversal to find the node.

example
java
// Simulating DOM traversal
class DOMNode {
    String tagName;
    String id;
    List<DOMNode> children = new ArrayList<>();
    
    // ... constructor ...
}

public DOMNode getElementById(DOMNode current, String targetId) {
    if (current == null) return null;
    if (targetId.equals(current.id)) return current;
    
    for (DOMNode child : current.children) {
        DOMNode result = getElementById(child, targetId);
        if (result != null) return result;
    }
    return null;
}

Check Your Knowledge

Test your understanding of Binary Trees with these quick questions.

Question 1

What defines a Binary Tree?

Question 2

What is the primary risk of using recursion on an extremely deep, unbalanced Binary Tree?

Question 3

If a node has no children, what is it called?

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

Binary Trees

Overview

A Binary Tree is a hierarchical data structure where every node has at most two children, referred to as the left child and the right child.

Unlike linear data structures (arrays, linked lists) where data is traversed sequentially, trees allow for branching. The top node is the root, and nodes with no children are leaves. Trees inherently represent hierarchical data: file systems, company org charts, XML/HTML document object models (DOM), and routing protocols all rely on tree structures.

The true power of a Binary Tree lies in its recursive nature. Every child node is itself the root of a smaller 'subtree'. This means nearly every operation on a binary tree (searching, traversing, calculating height) can be elegantly solved using a few lines of recursive code. However, a pure Binary Tree has no ordering rules regarding where data is placed, meaning searching for a specific value still requires checking every node (O(N) time).

Syntax

Defining and Building a Binary Tree
java
public class BinaryTree {
    // Standard Binary Tree Node
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        
        TreeNode(int val) {
            this.val = val;
        }
    }
    
    public static void main(String[] args) {
        // Constructing a small tree manually
        //       1
        //      /         //     2   3
        //    /
        //   4
        
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        
        // Calculating height recursively
        System.out.println("Tree Height: " + getHeight(root)); // Output: 3
    }
    
    // The beauty of trees: Recursive logic is trivial
    public static int getHeight(TreeNode node) {
        if (node == null) return 0; // Base case
        
        int leftHeight = getHeight(node.left);
        int rightHeight = getHeight(node.right);
        
        return Math.max(leftHeight, rightHeight) + 1;
    }
}

Common Pitfalls

  • NullPointerExceptions during traversal. Before accessing node.left or node.right, you must always ensure node != null. The base case of almost every recursive tree algorithm should be if (node == null) return ...;.
  • StackOverflowError on deeply unbalanced trees. If a tree heavily leans to one side (essentially becoming a linked list), recursive algorithms will push O(N) frames onto the call stack. For a tree with 50,000 nodes, this will crash the JVM. In production, highly unbalanced trees often require iterative solutions or self-balancing structures.
  • Losing track of the root node. In many tree modifications, if you reassign the root reference locally without returning or updating the global structure, you'll lose the tree entirely.

Interview Questions

What is the difference between a Full Binary Tree and a Complete Binary Tree?

In a Full Binary Tree, every node has exactly 0 or 2 children (no node has only 1 child). In a Complete Binary Tree, every level is completely filled except possibly the last level, and all nodes in the last level are as far left as possible. Complete Binary Trees are the foundation of Heaps.

Why do we use recursion so heavily with trees?

Because trees are inherently recursive data structures. A tree consists of a root node and two subtrees, which are themselves trees. Therefore, solving a problem for a single node and recursively delegating the same problem to its children naturally traverses the entire structure with minimal code.

Real-World Example

The HTML DOM (Document Object Model) that renders every web page is a tree structure (though generally an N-ary tree, not strictly binary). When JavaScript executes document.getElementById(), the browser performs a tree traversal to find the node.

example
java
// Simulating DOM traversal
class DOMNode {
    String tagName;
    String id;
    List<DOMNode> children = new ArrayList<>();
    
    // ... constructor ...
}

public DOMNode getElementById(DOMNode current, String targetId) {
    if (current == null) return null;
    if (targetId.equals(current.id)) return current;
    
    for (DOMNode child : current.children) {
        DOMNode result = getElementById(child, targetId);
        if (result != null) return result;
    }
    return null;
}

Check Your Knowledge

Test your understanding of Binary Trees with these quick questions.

Question 1

What defines a Binary Tree?

Question 2

What is the primary risk of using recursion on an extremely deep, unbalanced Binary Tree?

Question 3

If a node has no children, what is it called?

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