forked from jyxia/LeetCode-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path94-binaryTreeInorder.js
47 lines (44 loc) · 1.14 KB
/
94-binaryTreeInorder.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function(root) {
var stack = [];
var order = [];
while (stack.length > 0 || root) {
if (root) {
stack.push(root);
root = root.left;
} else {
var node = stack.pop();
order.push(node.val);
if (node.right) root = node.right;
}
}
return order;
};
// more concise and efficient
// as long as the left child is not empty, push it to the stack
// once left child reaches to the end (leaf), pop the last left, and visit,
// then assign its right node to be root, and repeat the process on current root (the right child)
var inorderTraversal = function(root) {
var stack = [];
var order = [];
while (root || stack.length > 0) {
while (root) {
stack.push(root);
root = root.left;
}
var node = stack.pop();
order.push(node.val);
root = node.right;
}
return order;
};