-
Notifications
You must be signed in to change notification settings - Fork 0
/
111_Minimum Depth of Binary Tree.js
50 lines (42 loc) · 1.1 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
// https://leetcode.com/problems/minimum-depth-of-binary-tree/tabs/description
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
/**
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function (root) {
var min;
var getPath = function (node, depth) {
if (!node || (min !== undefined && depth > min)) return;
var tempPath = depth + 1;
if (!node.left && !node.right) {
if (!min || min > tempPath) min = tempPath;
return;
}
getPath(node.left, tempPath);
getPath(node.right, tempPath);
}
getPath(root, 0);
return min || 0;
};
var root = new TreeNode(5);
root.left = new TreeNode(4);
root.left.left = new TreeNode(11);
root.left.left.left = new TreeNode(7);
root.left.left.right = new TreeNode(2);
root.right = new TreeNode(8);
root.right.left = new TreeNode(13);
root.right.right = new TreeNode(4);
root.right.right.right = new TreeNode(1);
console.log(minDepth(root));
console.log(minDepth(null));