Skip to content

Commit ae3dd65

Browse files
committed
Use iterative way to solve inorder traversal.
1 parent f444222 commit ae3dd65

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed

src/tree/binary-tree-inorder-traversal.js

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,20 +13,22 @@
1313
* Note: Recursive solution is trivial, could you do it iteratively?
1414
*/
1515
const inorderTraversal = root => {
16-
const res = [];
16+
const result = [];
17+
const stack = [];
18+
let current = root;
1719

18-
const helper = (root, res) => {
19-
if (!root) {
20-
return;
20+
while (stack.length || current) {
21+
if (current) {
22+
stack.push(current);
23+
current = current.left;
24+
} else {
25+
current = stack.pop();
26+
result.push(current.val);
27+
current = current.right;
2128
}
29+
}
2230

23-
helper(root.left, res);
24-
res.push(root.val);
25-
helper(root.right, res);
26-
};
27-
28-
helper(root, res);
29-
return res;
31+
return result;
3032
};
3133

3234
export default inorderTraversal;

0 commit comments

Comments
 (0)