Knowledge Guide
HomeDSATrees

Introduction to Tree Depth Pattern

The Tree Depth Pattern is crucial in binary tree problems where understanding the depth of the tree is key. Depth refers to the number of nodes along the path from the root to the deepest or shallowest leaf. Problems involving depth often require finding the minimum or maximum depth of the tree, which can be important for understanding the tree’s structure, balance, and overall health. Mastering this pattern will help you solve various problems efficiently by focusing on how deep or shallow different parts of the tree are.

To approach these problems, the general strategy involves traversing the tree while keeping track of the depth at each level. There are two common methods:

By understanding and applying these techniques, you'll be able to handle problems related to tree depth effectively, ensuring that you can identify the key characteristics of the tree structure quickly.

Now, let's understand to find the depth of particular node via example below.

Problem Statement

Given a root of the binary tree and node value n, return the depth of the node having value n in the tree. If the node does not exist in the tree, return -1.

Examples

Example 1:

Image
Image

Example 2:

Image
Image

Finding a Tree Depth Using the DFS

Here, the goal is to find the depth of a specific node by exploring the tree's structure, starting from the root and moving down each branch. DFS is effective here because it allows us to explore each possible path to the node, ensuring we find the exact depth. By keeping track of the current depth at each level, we can determine the node's position in the tree. This approach is efficient as it only traverses paths that are necessary to find the target node, making it optimal for solving this problem.

Step-by-Step Algorithm

Here’s a detailed explanation of the DFS algorithm to find the depth of a given node in a binary tree:

Algorithm Walkthrough

Let's walk through the algorithm with a real input to see how it works:

Image
Image

Walkthrough:

Code

java
// class TreeNode {
//     int val;
//     TreeNode left, right;

//     TreeNode(int val) {
//         this.val = val;
//         this.left = null;
//         this.right = null;
//     }
// }

public class Solution {


    public int findDepth(TreeNode root, int target) {
        return dfs(root, target, 1); // Start DFS from root at depth 1
    }

    private int dfs(TreeNode node, int target, int depth) {
        // Base case: if node is null, return -1 (target not found)
        if (node == null) {
            return -1;
        }

        // If current node is the target, return current depth
        if (node.val == target) {
            return depth;
        }

        // Recur for the left subtree
        int leftDepth = dfs(node.left, target, depth + 1);
        if (leftDepth != -1) {
            return leftDepth; // Target found in left subtree
        }

        // Recur for the right subtree if not found in left
        return dfs(node.right, target, depth + 1); // Check right subtree
    }

    public static void main(String[] args) {
        // Creating the binary tree
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);

        // Creating an instance of the Solution class
        Solution solution = new Solution();

        // Test case 1: Finding depth of node with value 15
        int depth1 = solution.findDepth(root, 15);
        System.out.println("Depth of node 15: " + depth1); // Expected output: 3
    }
}

Complexity Analysis

Finding a Tree Depth Using the BFS

The BFS also is ideal for this type of problem because it explores the tree level by level, making it well-suited for finding the shortest path or depth in a binary tree. By processing all nodes at one depth level before moving to the next, BFS ensures that we find the target node at the shallowest possible depth, if it exists. This approach is effective because it avoids unnecessary deep exploration and directly focuses on the level where the target node resides. Additionally, BFS naturally handles the traversal in a way that keeps track of the depth, making it easy to return the correct depth as soon as the target node is found.

Step-by-Step Algorithm

  1. Check for an empty tree:

    • If root is null, return -1.
  2. Initialize the queue:

    • Create a queue and add the root node with depth 1.
  3. Begin BFS traversal:

    • While the queue is not empty, do the following:
      • Determine the number of nodes at the current level (levelSize).
  4. Process each node at the current level:

    • For each node in the current level:
      • Dequeue the node.
      • If the node’s value matches the target, return the current depth.
      • Add the left and right children (if they exist) to the queue with an incremented depth.
  5. Increment depth:

    • After processing all nodes at the current level, increment the depth by 1.
  6. Return -1:

    • If the queue is empty and the target node was not found, return -1.

Algorithm Walkthrough

Image
Image

Initial State:

Steps:

  1. Level 1:

    • Queue before processing: [3]
    • Dequeue 3.
    • 3 does not match 15.
    • Add 9 and 20 to the queue.
    • Queue after processing: [9, 20]
    • Increment depth to 2.
    • Depth: 2
  2. Level 2:

    • Queue before processing: [9, 20]
    • Dequeue 9.
    • 9 does not match 15. It has no children.
    • Queue after processing 9: [20]
    • Dequeue 20.
    • 20 does not match 15.
    • Add 15 and 7 to the queue.
    • Queue after processing 20: [15, 7]
    • Increment depth to 3.
    • Depth: 3
  3. Level 3:

    • Queue before processing: [15, 7]
    • Dequeue 15.
    • 15 matches the target node.
    • Return depth: 3

Final Output: The depth of node 15 is 3.

Code

java
import java.util.LinkedList;
import java.util.Queue;

// class TreeNode {
//     int val;
//     TreeNode left, right;

//     TreeNode(int val) {
//         this.val = val;
//         this.left = null;
//         this.right = null;
//     }
// }


public class Solution {

    // BFS method to find the depth of a given node value
    public int findDepth(TreeNode root, int target) {
        // If the tree is empty, return -1
        if (root == null) {
            return -1;
        }

        // Initialize a queue to store nodes along with their depth
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int depth = 1; // Start from depth 1

        // Perform BFS traversal
        while (!queue.isEmpty()) {
            int levelSize = queue.size(); // Number of nodes at the current depth level

            // Process all nodes at the current level
            for (int i = 0; i < levelSize; i++) {
                TreeNode currentNode = queue.poll();

                // If the current node matches the target, return the current depth
                if (currentNode.val == target) {
                    return depth;
                }

                // Add left and right children to the queue, if they exist
                if (currentNode.left != null) {
                    queue.add(currentNode.left);
                }
                if (currentNode.right != null) {
                    queue.add(currentNode.right);
                }
            }

            // Increment depth as we move to the next level
            depth++;
        }

        // If the target node is not found, return -1
        return -1;
    }

    // Main method to test the algorithm
    public static void main(String[] args) {
        // Creating the binary tree
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);

        // Creating an instance of the Solution class
        Solution solution = new Solution();

        // Test case 1: Finding depth of node with value 15
        int depth1 = solution.findDepth(root, 15);
        System.out.println("Depth of node 15: " + depth1); // Expected output: 3
    }
}

Complexity Analysis:

🤖 Don't fully get this? Learn it with Claude

Stuck on Introduction to Tree Depth Pattern? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **Introduction to Tree Depth Pattern** (DSA) and want to truly understand it. Explain Introduction to Tree Depth Pattern from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **Introduction to Tree Depth Pattern** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **Introduction to Tree Depth Pattern** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **Introduction to Tree Depth Pattern** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes