-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path104MaxDepthBTree.js
More file actions
37 lines (34 loc) · 902 Bytes
/
Copy path104MaxDepthBTree.js
File metadata and controls
37 lines (34 loc) · 902 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
36
37
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
if(root == null) return 0;
let queue = [];
let depth = 0;
queue.push(root)
while(queue.length > 0){
let numOfNodes = queue.length;
for(let i = 0; i<numOfNodes;i++){
let current = queue.shift();
if(current.left) queue.push(current.left);
if(current.right) queue.push(current.right);
}
depth++;
}
return depth;
};
var maxDepth2 = function(root) {
if(root == null) return 0;
let left = maxDepth(root.left);
let right = maxDepth(root.right);
return Math.max(left,right) +1;
};