diff --git a/javascript/0104-maximum-depth-of-binary-tree.js b/javascript/0104-maximum-depth-of-binary-tree.js index 0607e0160..9b2b7a8af 100644 --- a/javascript/0104-maximum-depth-of-binary-tree.js +++ b/javascript/0104-maximum-depth-of-binary-tree.js @@ -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; @@ -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} */ @@ -31,7 +57,7 @@ var maxDepth = function(root) { if (isBaseCase) return 0; return bfs([[ root, 0 ]]); -} +}; const bfs = (queue, height = 0) => { while (queue.length) { @@ -46,5 +72,4 @@ const bfs = (queue, height = 0) => { } return height; -} - +};