-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
35 lines (29 loc) · 877 Bytes
/
Solution.java
File metadata and controls
35 lines (29 loc) · 877 Bytes
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
31
32
33
34
35
/**
* 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 minDepth(TreeNode root) {
if (root == null)
return 0;
return getDepth(root, 1);
}
private int getDepth(TreeNode node, int depth) {
if (node.left == null && node.right == null)
return depth;
int leftDepth = Integer.MAX_VALUE;
int rightDepth = Integer.MAX_VALUE;
if (node.left != null) {
leftDepth = getDepth(node.left, depth + 1);
}
if (node.right != null) {
rightDepth = getDepth(node.right, depth + 1);
}
return leftDepth < rightDepth ? leftDepth : rightDepth;
}
}