-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathMinimumDepthOfBinaryTree.java
More file actions
64 lines (51 loc) · 1.31 KB
/
MinimumDepthOfBinaryTree.java
File metadata and controls
64 lines (51 loc) · 1.31 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Example
Given a binary tree as follow:
1
/ \
2 3
/ \
4 5
The minimum depth is 2
Tags Expand
Depth First Search
Thinking Process:
Note: a little different from maxDepth:
If 1,#,2: the left route 1-# does not count as a path, so the minDepth is actually 2 in this example.
We need a helper function to calculate the minimum.
*/
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: An integer.
*/
//recursive:
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
return getMin(root);
}
public int getMin(TreeNode root) {
if (root == null) {
return Integer.MAX_VALUE;
}
if (root.left == null && root.right == null) {
return 1;
}
return Math.min(getMin(root.left), getMin(root.right)) + 1;
}
}