Maximum Depth of Binary Tree

Maximum Depth of Binary Tree

Coding Solution

·

1 min read

Problem

Given the root of the binary tree, find its maximum depth. This is similar to the Leetcode Problem - Maximum Depth of Binary Tree

Approach

The approach would be based on recursion where we traverse through the left and right nodes of the tree and find the maximum among them.

class Solution {
    public int maxDepth(TreeNode root) {
int l = 0, r=0;
        if(root == null){
            return 0;
        }
        if(root.left != null){
            l = 1 + maxDepth(root.left);
        } 
        if(root.right != null){
            r = 1 + maxDepth(root.right);
        }
        if(root.left == null && root.right == null){
            return 1;
        }        
        return Math.max(l,r);
    }
}

Do have a look at the discuss section for more optimized solutions if available - LeetCode Discuss