1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Tree Dfs
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
10Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Tree Dfs

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
10Secs
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

Tree DFS

Overview

Depth-First Search (DFS) on a Binary Tree traverses by going as deep as possible down a single path before retreating (backtracking) to explore a different path.

While BFS uses a Queue (FIFO) to explore broadly, DFS fundamentally relies on a Stack (LIFO) to dive deep. Because the JVM itself operates using a Call Stack, Tree DFS is almost universally written using Recursion, resulting in incredibly elegant, 3-line algorithms that leverage the compiler to manage the stack for you.

DFS is the algorithmic tool of choice when you need to inspect complete paths from root to leaves, or when you are searching for a node that you strongly suspect is located deep at the bottom of the tree. Furthermore, it is significantly more memory-efficient than BFS for wide, bushy trees, requiring only O(H) space, where H is the height of the tree (which is just O(log N) in a balanced tree, compared to BFS's O(N)).

Syntax

Basic Recursive DFS
java
public class TreeDFS {
    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    // A fundamental recursive DFS template
    public void dfs(TreeNode root) {
        // 1. Base Case: Reached the bottom or an empty tree
        if (root == null) {
            return; 
        }
        
        // 2. Process current node (Pre-Order logic goes here)
        System.out.println("Visiting: " + root.val);
        
        // 3. Recurse deep down the left side
        dfs(root.left);
        
        // 4. Recurse deep down the right side
        dfs(root.right);
    }
    
    // DFS is perfect for calculating Tree Height recursively
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        
        return Math.max(leftDepth, rightDepth) + 1;
    }
}

Common Pitfalls

  • StackOverflowError on 'Degenerate' trees. A degenerate tree is a tree where every node only has one child, effectively forming a straight Linked List. If this list has 50,000 nodes, a recursive DFS will push 50,000 frames to the JVM Call Stack and crash. Iterative DFS (using java.util.Stack) is required for massive unbalanced trees in production.
  • Returning values prematurely. In algorithms searching for a specific node, beginners often write dfs(node.left); return true;. This skips checking the right side entirely! You must capture the result: boolean foundLeft = dfs(node.left); if (foundLeft) return true;.
  • Using Global variables to store state. Storing results in a class-level variable int count = 0; works in single LeetCode test cases but fails catastrophically in multi-threaded production servers. Always pass state down via method arguments or return it up the recursive chain.

Interview Questions

What is the Space Complexity of Recursive DFS?

The space complexity is determined by the maximum depth of the call stack, which equals the Height of the tree: O(H). In a perfectly balanced tree, this is O(log N). In a completely unbalanced tree, it degrades to O(N).

How would you implement DFS iteratively without using recursion?

By explicitly managing your own java.util.ArrayDeque acting as a Stack. You push the root. In a while loop, you pop a node, process it, and then explicitly push its right child first, followed by its left child (so the left child is at the top of the stack and gets popped and processed first).

Real-World Example

Compilers evaluating Abstract Syntax Trees (AST). When you write (5 + 3) * 2 in code, the compiler parses this and builds a tree where * is the root, + is the left child, and 2 is the right. The compiler evaluates this using a post-order DFS: it must go as deep as possible to evaluate (5 + 3) before it can return that value up to perform the multiplication.

example
java
class ASTNode {
    String value;
    ASTNode left, right;
    boolean isLeaf() { return left == null && right == null; }
}

public class CompilerAST {
    // Evaluating a math expression tree using DFS
    public int evaluate(ASTNode node) {
        if (node.isLeaf()) {
            return Integer.parseInt(node.value);
        }
        
        // Deep DFS to get evaluated child values FIRST
        int leftVal = evaluate(node.left);
        int rightVal = evaluate(node.right);
        
        // Then process the current node based on the operator
        if (node.value.equals("+")) return leftVal + rightVal;
        if (node.value.equals("*")) return leftVal * rightVal;
        if (node.value.equals("-")) return leftVal - rightVal;
        
        return 0;
    }
}

Check Your Knowledge

Test your understanding of Tree DFS with these quick questions.

Question 1

What underlying concept natively powers standard recursive DFS?

Question 2

Why might recursive DFS be dangerous in production code?

Question 3

What is the Space Complexity of DFS on a perfectly balanced tree of N nodes?

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

Tree DFS

Overview

Depth-First Search (DFS) on a Binary Tree traverses by going as deep as possible down a single path before retreating (backtracking) to explore a different path.

While BFS uses a Queue (FIFO) to explore broadly, DFS fundamentally relies on a Stack (LIFO) to dive deep. Because the JVM itself operates using a Call Stack, Tree DFS is almost universally written using Recursion, resulting in incredibly elegant, 3-line algorithms that leverage the compiler to manage the stack for you.

DFS is the algorithmic tool of choice when you need to inspect complete paths from root to leaves, or when you are searching for a node that you strongly suspect is located deep at the bottom of the tree. Furthermore, it is significantly more memory-efficient than BFS for wide, bushy trees, requiring only O(H) space, where H is the height of the tree (which is just O(log N) in a balanced tree, compared to BFS's O(N)).

Syntax

Basic Recursive DFS
java
public class TreeDFS {
    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    // A fundamental recursive DFS template
    public void dfs(TreeNode root) {
        // 1. Base Case: Reached the bottom or an empty tree
        if (root == null) {
            return; 
        }
        
        // 2. Process current node (Pre-Order logic goes here)
        System.out.println("Visiting: " + root.val);
        
        // 3. Recurse deep down the left side
        dfs(root.left);
        
        // 4. Recurse deep down the right side
        dfs(root.right);
    }
    
    // DFS is perfect for calculating Tree Height recursively
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        
        return Math.max(leftDepth, rightDepth) + 1;
    }
}

Common Pitfalls

  • StackOverflowError on 'Degenerate' trees. A degenerate tree is a tree where every node only has one child, effectively forming a straight Linked List. If this list has 50,000 nodes, a recursive DFS will push 50,000 frames to the JVM Call Stack and crash. Iterative DFS (using java.util.Stack) is required for massive unbalanced trees in production.
  • Returning values prematurely. In algorithms searching for a specific node, beginners often write dfs(node.left); return true;. This skips checking the right side entirely! You must capture the result: boolean foundLeft = dfs(node.left); if (foundLeft) return true;.
  • Using Global variables to store state. Storing results in a class-level variable int count = 0; works in single LeetCode test cases but fails catastrophically in multi-threaded production servers. Always pass state down via method arguments or return it up the recursive chain.

Interview Questions

What is the Space Complexity of Recursive DFS?

The space complexity is determined by the maximum depth of the call stack, which equals the Height of the tree: O(H). In a perfectly balanced tree, this is O(log N). In a completely unbalanced tree, it degrades to O(N).

How would you implement DFS iteratively without using recursion?

By explicitly managing your own java.util.ArrayDeque acting as a Stack. You push the root. In a while loop, you pop a node, process it, and then explicitly push its right child first, followed by its left child (so the left child is at the top of the stack and gets popped and processed first).

Real-World Example

Compilers evaluating Abstract Syntax Trees (AST). When you write (5 + 3) * 2 in code, the compiler parses this and builds a tree where * is the root, + is the left child, and 2 is the right. The compiler evaluates this using a post-order DFS: it must go as deep as possible to evaluate (5 + 3) before it can return that value up to perform the multiplication.

example
java
class ASTNode {
    String value;
    ASTNode left, right;
    boolean isLeaf() { return left == null && right == null; }
}

public class CompilerAST {
    // Evaluating a math expression tree using DFS
    public int evaluate(ASTNode node) {
        if (node.isLeaf()) {
            return Integer.parseInt(node.value);
        }
        
        // Deep DFS to get evaluated child values FIRST
        int leftVal = evaluate(node.left);
        int rightVal = evaluate(node.right);
        
        // Then process the current node based on the operator
        if (node.value.equals("+")) return leftVal + rightVal;
        if (node.value.equals("*")) return leftVal * rightVal;
        if (node.value.equals("-")) return leftVal - rightVal;
        
        return 0;
    }
}

Check Your Knowledge

Test your understanding of Tree DFS with these quick questions.

Question 1

What underlying concept natively powers standard recursive DFS?

Question 2

Why might recursive DFS be dangerous in production code?

Question 3

What is the Space Complexity of DFS on a perfectly balanced tree of N nodes?

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