-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path111.minimum-depth-of-binary-tree.js
67 lines (60 loc) · 1.35 KB
/
111.minimum-depth-of-binary-tree.js
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
64
65
66
67
/*
✔ Accepted
✔ 41/41 cases passed (68 ms)
✔ Your runtime beats 18.32 % of javascript submissions
* [111] Minimum Depth of Binary Tree
*
* https://leetcode.com/problems/minimum-depth-of-binary-tree/description/
*
* algorithms
* Easy (34.14%)
* Total Accepted: 243.3K
* Total Submissions: 712.6K
* Testcase Example: '[3,9,20,null,null,15,7]'
*
* 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.
*
* Note: A leaf is a node with no children.
*
* Example:
*
* Given binary tree [3,9,20,null,null,15,7],
*
*
* 3
* / \
* 9 20
* / \
* 15 7
*
* return its minimum depth = 2.
*
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function(root) {
if (root === null) return 0;
return _minDepth(root);
};
var _minDepth = function(root) {
if (root.left === null && root.right === null) return 1;
let leftDepth = Infinity,
rightDepth = Infinity;
if (root.left)
leftDepth = minDepth(root.left);
if (root.right)
rightDepth = minDepth(root.right);
return 1 + Math.min(leftDepth, rightDepth);
}