Finding the max depth of the binary tree

Jolly srivastava
1 min readDec 1, 2020

Leetcode: https://leetcode.com/explore/featured/card/december-leetcoding-challenge/569/week-1-december-1st-december-7th/3551/

Max depth: The maximum depth of a binary tree is the number of nodes from the root down to the furthest leaf node.

e.g:

MAX DEPTH = MAX(height of left subtree, height of right subtree)

As per the above image, Height of left subtree = 4 (i.e nodes 2,7,6,11)

and Height of right subtree= 4 (i.e nodes 2,5,9,4)

Therefore,MAX DEPTH = 4 ( as here height of LST and RST is same)

ALGORITHIM:

  1. Recursively find the height of LST.
  2. Recursively find the height of RST.
  3. Return the max among them.

JAVA CODE:

public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}

class Solution {
public int maxDepth(TreeNode root) {
int height = maxHeight(root);
return height;
}

public int maxHeight(TreeNode root){

if(root == null){
return 0;
}

int ans = 0;
int left = maxHeight(root.left);
int right = maxHeight(root.right);

if(left > right){
return left+1;
}
else{
return right+1;
}

}
}

--

--