-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree_traversal_it.js
82 lines (73 loc) · 1.49 KB
/
tree_traversal_it.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { root } from './tree';
`
1
/ \
2 3
/ \ / \
4 5 6 7
`;
function inOrderTraversal(root) {
`
left -> root -> right
4 -> 2 -> 5 -> 1 -> 6 -> 3 -> 7
`;
const stack = [];
while (true) {
while (root) {
stack.push(root);
root = root.left;
}
if (stack.length === 0) break;
let node = stack.pop();
console.log(node.val);
if (node.right) {
root = node.right;
}
}
}
console.log('In order traversal');
// inOrderTraversal(root);
function preOrderTraversal(root) {
`
root -> left -> right
1 -> 2 -> 4 -> 5 -> 3 -> 6 -> 7
`;
const stack = [];
while (true) {
while (root) {
console.log(root.val);
stack.push(root);
root = root.left;
}
if (stack.length === 0) break;
let node = stack.pop();
if (node.right) {
root = node.right;
}
}
}
console.log('Pre order traversal');
// preOrderTraversal(root);
function postOrderTraversal(root) {
`
left -> right -> root
4 -> 5 -> 2 -> 6 -> 7 -> 3 -> 1
`;
const stack = [];
while (true) {
while (root) {
stack.push(root);
root = root.left;
}
if (stack.length == 0) break;
let node = stack[stack.length - 1];
if (node.right) {
root = node.right;
} else {
let temp = stack.pop();
console.log(temp.val);
}
}
}
console.log('Post order traversal');
postOrderTraversal(root);