Skip to content

Commit c6635e8

Browse files
Update Merge Two Binary Trees.md
1 parent 600c23f commit c6635e8

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

JS-Algo/Merge Two Binary Trees.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,30 @@ var mergeTrees = function(t1, t2) {
3939
return t1
4040
};
4141
```
42+
43+
44+
Extra: Stack solution
45+
46+
```JS
47+
const mergeTrees = (t1, t2) => {
48+
if (!t1 || !t2)
49+
return t1 || t2;
50+
const stack = Array();
51+
stack.push([t1, t2]);
52+
while (stack.length > 0) {
53+
const pair = stack.pop();
54+
if (!pair[0] || !pair[1])
55+
continue;
56+
pair[0].val += pair[1].val;
57+
if (!pair[0].left)
58+
pair[0].left = pair[1].left;
59+
else
60+
stack.push([pair[0].left, pair[1].left]);
61+
if (!pair[0].right)
62+
pair[0].right = pair[1].right;
63+
else
64+
stack.push([pair[0].right, pair[1].right]);
65+
}
66+
return t1;
67+
};
68+
```

0 commit comments

Comments
 (0)