-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtraversals.js
More file actions
38 lines (34 loc) · 914 Bytes
/
traversals.js
File metadata and controls
38 lines (34 loc) · 914 Bytes
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
/**
* @param {TreeNode} root
* @return {number[]}
* This algorithm works by iterating through the tree "in-place",
* without using any additional stack or queue data structures.
* This is what allows it to have a space complexity of O(1).
* Time O(n)
* Space O(1)
* Preorder Traversal
*/
var preorderTraversal = function (root) {
let current = root;
let result = [];
while (current) {
if (!current.left) {
result.push(current.val);
current = current.right;
} else {
let predecessor = current.left;
while (predecessor.right && predecessor.right !== current) {
predecessor = predecessor.right;
}
if (!predecessor.right) {
result.push(current.val);
predecessor.right = current;
current = current.left;
} else {
predecessor.right = null;
current = current.right;
}
}
}
return result;
};