Skip to content

Commit 5df07d9

Browse files
committed
add tree traversal algorithms
1 parent 5b8052b commit 5df07d9

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

binary-trees/traversals.js

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* @param {TreeNode} root
3+
* @return {number[]}
4+
* This algorithm works by iterating through the tree "in-place",
5+
* without using any additional stack or queue data structures.
6+
* This is what allows it to have a space complexity of O(1).
7+
* Time O(n)
8+
* Space O(1)
9+
* Preorder Traversal
10+
*/
11+
var preorderTraversal = function (root) {
12+
let current = root;
13+
let result = [];
14+
15+
while (current) {
16+
if (!current.left) {
17+
result.push(current.val);
18+
current = current.right;
19+
} else {
20+
let predecessor = current.left;
21+
22+
while (predecessor.right && predecessor.right !== current) {
23+
predecessor = predecessor.right;
24+
}
25+
26+
if (!predecessor.right) {
27+
result.push(current.val);
28+
predecessor.right = current;
29+
current = current.left;
30+
} else {
31+
predecessor.right = null;
32+
current = current.right;
33+
}
34+
}
35+
}
36+
37+
return result;
38+
};

0 commit comments

Comments
 (0)