-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmax-depth-binary-tree.js
More file actions
64 lines (53 loc) · 1.29 KB
/
Copy pathmax-depth-binary-tree.js
File metadata and controls
64 lines (53 loc) · 1.29 KB
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
// https://leetcode.com/problems/maximum-depth-of-binary-tree/
// Related Topics: Tree, DFS
// Difficulty: Easy
/*
Initial thoughts:
Using a DFS algorithm, we are going to recursively traverse each path
until we encounter a leaf node (both childs are null), counting the depth
and comparing the results to get the max.
Time complexity: O(n) in the worst case when the tree is fully unbalanced
Space complexity: O(n) for the recursive stack
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
const maxDepth = root => {
// base case
if (!root) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
};
/*
Iterative approach
Time complexity: O(n)
Space complexity: O(n) we need to use a stack to follow the depth
*/
/**
* @param {TreeNode} root
* @return {number}
*/
const maxDepth = root => {
if (!root) return 0;
let stack = [root];
let tempStack = [];
let count = 0;
while (stack.length) {
let temp = stack.pop();
if (temp.left) tempStack.push(temp.left);
if (temp.right) tempStack.push(temp.right);
if (!stack.length) {
count++;
stack = tempStack;
tempStack = [];
}
}
return count;
};