-
Notifications
You must be signed in to change notification settings - Fork 279
/
111 Minimum Depth of Binary Tree.js
56 lines (46 loc) · 1.08 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
// Leetcode 111
// Language: Javascript
// Problem: https://leetcode.com/problems/minimum-depth-of-binary-tree/
// Author: Chihung Yu
/**
* 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;
}
var queue = [];
queue.push(root);
var height = 1;
var curLvlCnt = 1;
var nextLvlCnt = 0;
while(queue.length !== 0){
var node = queue.shift();
curLvlCnt--;
if(node.left){
queue.push(node.left);
nextLvlCnt++;
}
if(node.right){
queue.push(node.right);
nextLvlCnt++;
}
if(node.left === null && node.right === null){
return height;
}
if(curLvlCnt === 0){
height++;
curLvlCnt = nextLvlCnt;
nextLvlCnt = 0;
}
}
return height;
};