forked from jyxia/LeetCode-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path144-binaryTreePreorder.js
47 lines (44 loc) · 1.07 KB
/
144-binaryTreePreorder.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;
* }
*/
/**
* key: rightNodes is the stack to track right nodes.
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function(root) {
var rightNodes = [];
var order = [];
while (root || rightNodes.length > 0) {
if (root) {
order.push(root.val);
if (root.right) rightNodes.push(root.right);
root = root.left;
} else {
root = rightNodes.pop();
}
}
return order;
};
// this is a more straightforward method, but slower than first one.
// stack tracks the node visit order
var preorderTraversal = function(root) {
if (!root) return [];
var result = [];
var stack = [root];
while (stack.length > 0) {
var node = stack.pop();
result.push(node.val);
if (node.right) {
stack.push(node.right);
}
if (node.left) {
stack.push(node.left);
}
}
return result;
};