Maximum Depth of Binary Tree

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: 3

Example 2:

Input: root = [1,null,2]
Output: 2
class Solution {
    public int maxDepth(TreeNode root) {
        
        if(root==null) return 0;
        int d1 = maxDepth(root.left);
        int d2 = maxDepth(root.right);
        
        return Math.max(d1,d2)+1;      
    }
}
Explanation
1. Calculate the depth of the left subtree and right tree.
2. Get max of left and right sub tree.
3. Depth of tree is max + 1 as include root node also.
4. Base condition is root is null then return 0.



Comments

Popular posts from this blog

Java 8 : Find the number starts with 1 from a list of integers

Junit Mockito and Power Mockito

Important Linux Commands