Skip to content

Commit

Permalink
Merge pull request #2716 from eunicode/0104-iterative-dfs
Browse files Browse the repository at this point in the history
  • Loading branch information
aakhtar3 authored Jul 19, 2023
2 parents f536d27 + db47f7c commit 0dbde16
Showing 1 changed file with 32 additions and 7 deletions.
39 changes: 32 additions & 7 deletions javascript/0104-maximum-depth-of-binary-tree.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
/**
* https://leetcode.com/problems/maximum-depth-of-binary-tree/
* TIme O(N) | Space O(N)
* Time O(N) | Space O(N)
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
var maxDepth = function(root) {
const isBaseCase = root === null;
if (isBaseCase) return 0;

Expand All @@ -18,11 +18,37 @@ const dfs = (root) => {
const height = Math.max(left, right);

return height + 1;
}
};

/**
* https://leetcode.com/problems/maximum-depth-of-binary-tree/
* TIme O(N) | Space O(N)
* Time O(N) | Space O(N)
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
const isBaseCase = root === null;
if (isBaseCase) return 0;

return iterativeDfs([[root, 1]]);
};

const iterativeDfs = (stack, height = 0) => {
while (stack.length) {
const [root, depth] = stack.pop();

height = Math.max(height, depth);

if (root.right) stack.push([root.right, depth + 1]);
if (root.left) stack.push([root.left, depth + 1]);
}

return height;
};

/**
* https://leetcode.com/problems/maximum-depth-of-binary-tree/
* Time O(N) | Space O(N)
* @param {TreeNode} root
* @return {number}
*/
Expand All @@ -31,7 +57,7 @@ var maxDepth = function(root) {
if (isBaseCase) return 0;

return bfs([[ root, 0 ]]);
}
};

const bfs = (queue, height = 0) => {
while (queue.length) {
Expand All @@ -46,5 +72,4 @@ const bfs = (queue, height = 0) => {
}

return height;
}

};

0 comments on commit 0dbde16

Please sign in to comment.