-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0414_leetcode104.js
More file actions
31 lines (30 loc) · 899 Bytes
/
0414_leetcode104.js
File metadata and controls
31 lines (30 loc) · 899 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
/**
* 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){
return 0;
}
return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
};
//----------------------- BFS -----------------------------
var maxDepth = function(root) {
if(!root) return 0;
let queue = [{node: root, level: 1}], maxDepth = 0;
while(queue.length > 0){
let {node, level} = queue.shift();
maxDepth = Math.max(maxDepth, level);
if(node.left) queue.push({node: node.left, level: level+1});
if(node.right) queue.push({node: node.right, level: level+1})
}
return maxDepth;
}