-
Notifications
You must be signed in to change notification settings - Fork 0
/
traversals.js
66 lines (54 loc) · 1.55 KB
/
traversals.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
Pre-order traversal
1. Check if the current node is empty/null
2. Display the data part of the root (or current node)
3. Traverse the left subtree by recursively calling the pre-order function
4. Traverse the right subtree by recursively calling the pre-order function
*/
preOrder(node, preorder) {
if (!preorder) {
preorder = [];
}
if (node) {
preorder.push(node.data);
this.preOrder(node.left, preorder);
this.preOrder(node.right, preorder);
}
return preorder;
}
/*
In-order traversal
1. Check if the current node is empty/null
2. Traverse the left subtree by recursively calling the in-order function
3. Display the data part of the root (or current node)
4. Traverse the right subtree by recursively calling the in-order function
*/
inOrder(node, inorder) {
if (!inorder) {
inorder = [];
}
if (node) {
this.inOrder(node.left, inorder);
inorder.push(node.data);
this.inOrder(node.right, inorder);
}
return inorder;
}
/*
Post-order traversal
1. Check if the current node is empty/null
2. Traverse the left subtree by recursively calling the post-order function
3. Traverse the right subtree by recursively calling the post-order function
4. Display the data part of the root (or current node)
*/
postOrder(node, postorder) {
if (!postorder) {
postorder = [];
}
if (node) {
this.postOrder(node.left, postorder);
this.postOrder(node.right, postorder);
postorder.push(node.data);
}
return postorder;
}