From db47f7ce495cb047b02f3e8b802425663dae6765 Mon Sep 17 00:00:00 2001
From: Eunice Park <28845173+eunicode@users.noreply.github.com>
Date: Wed, 19 Jul 2023 12:34:09 -0700
Subject: [PATCH] Update 0104: Add iterative DFS solution (javascript)

---
 .../0104-maximum-depth-of-binary-tree.js      | 39 +++++++++++++++----
 1 file changed, 32 insertions(+), 7 deletions(-)

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;
-}
-
+};