We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent f444222 commit ae3dd65Copy full SHA for ae3dd65
src/tree/binary-tree-inorder-traversal.js
@@ -13,20 +13,22 @@
13
* Note: Recursive solution is trivial, could you do it iteratively?
14
*/
15
const inorderTraversal = root => {
16
- const res = [];
+ const result = [];
17
+ const stack = [];
18
+ let current = root;
19
- const helper = (root, res) => {
- if (!root) {
20
- return;
+ 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;
28
}
29
+ }
30
- helper(root.left, res);
- res.push(root.val);
- helper(root.right, res);
- };
-
- helper(root, res);
- return res;
31
+ return result;
32
};
33
34
export default inorderTraversal;
0 commit comments