Skip to content

Commit 57d5217

Browse files
committed
Create Binary Tree Inorder Traversal.js
1 parent aab49e4 commit 57d5217

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Diff for: Binary Tree Inorder Traversal.js

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
Given a binary tree, return the inorder traversal of its nodes' values.
3+
4+
For example:
5+
Given binary tree {1,#,2,3},
6+
1
7+
\
8+
2
9+
/
10+
3
11+
return [1,3,2].
12+
13+
Note: Recursive solution is trivial, could you do it iteratively?
14+
15+
* Definition for binary tree
16+
* function TreeNode(val) {
17+
* this.val = val;
18+
* this.left = this.right = null;
19+
* }
20+
*/
21+
22+
/**
23+
* @param {TreeNode} root
24+
* @returns {number[]}
25+
*/
26+
var inorderTraversal = function(root) {
27+
var stack = [],
28+
result = [],
29+
cur;
30+
cur = root;
31+
while (stack.length > 0 || cur !== null) {
32+
if (cur !== null) {
33+
stack.push(cur);
34+
cur = cur.left;
35+
} else {
36+
cur = stack.pop();
37+
result.push(cur.val);
38+
cur = cur.right;
39+
}
40+
}
41+
return result;
42+
};

0 commit comments

Comments
 (0)