LeetCode - 104 - Maximum Depth of Binary Tree

Problem

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.

1
2
3
4
5
6
7
8
9
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/

Note: Depth is started to count at 1. Try it out : https://leetcode.com/problems/maximum-depth-of-binary-tree/

Java 1ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
return searchDepth(root,1);
}
public int searchDepth(TreeNode root,int initDepth){
if (root == null){
return 0;
}else if (root.left == null && root.right == null){
return initDepth;
}else if (root.left != null && root.right == null){
return searchDepth(root.left, initDepth + 1);
}else if (root.right != null && root.left == null){
return searchDepth(root.right,initDepth+1);
}else if (root.right != null && root.left != null){
int leftDepth = searchDepth(root.left , initDepth+1);
int rightDepth = searchDepth(root.right, initDepth+1);
return leftDepth > rightDepth?leftDepth:rightDepth;
}
return 0;
}
}