Maximum Depth of Binary Tree

In this article, I explain about how to find the Maximum Depth of Binary Tree which is also called as Height of Binary Tree.

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.

Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    int h = 0;
    public int MaxDepth(TreeNode root) {
        
        if(root == null)
            return 0;
        int leftSubTreeHeight = MaxDepth(root.left);
        int rightSubTreeHeight = MaxDepth(root.right);
        
        
        if(leftSubTreeHeight > rightSubTreeHeight)
             h = 1 + leftSubTreeHeight;
        else
             h = 1 + rightSubTreeHeight;
        
        return h;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s