-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtreeTraversals.js
More file actions
executable file
·77 lines (58 loc) · 2.28 KB
/
treeTraversals.js
File metadata and controls
executable file
·77 lines (58 loc) · 2.28 KB
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
// Tree traversals: Inorder, Preorder, Postorder
// what is tree node?
// A tree node is a fundamental part of a tree data structure. It contains a value or data and may have references (or pointers) to its child nodes. Each node can be connected to multiple child nodes, forming the hierarchical structure of the tree.
// what is tree traversal?
// Tree traversal is the process of visiting all the nodes in a tree data structure in a specific order. The three most common types of tree traversals are Inorder, Preorder, and Postorder.
// Mental model:
// “Traversing a tree is like exploring a family tree or organizational chart, where you visit each person (node) in a specific sequence to gather information or perform actions.”
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
// Inorder Traversal (Left, Root, Right)
function inorderTraversal(node, result = []) {
if (node) {
inorderTraversal(node.left, result);
result.push(node.value);
inorderTraversal(node.right, result);
}
return result;
}
// Preorder Traversal (Root, Left, Right)
function preorderTraversal(node, result = []) {
if (node) {
result.push(node.value);
preorderTraversal(node.left, result);
preorderTraversal(node.right, result);
}
return result;
}
// Postorder Traversal (Left, Right, Root)
function postorderTraversal(node, result = []) {
if (node) {
postorderTraversal(node.left, result);
postorderTraversal(node.right, result);
result.push(node.value);
}
return result;
}
// Example usage:
// Creating a sample tree:
// 1
// / \
// 2 3
// / \
// 4 5
let root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
console.log("Inorder Traversal:", inorderTraversal(root)); // Output: [4, 2, 5, 1, 3]
console.log("Preorder Traversal:", preorderTraversal(root)); // Output: [1, 2, 4, 5, 3]
console.log("Postorder Traversal:", postorderTraversal(root)); // Output: [4, 5, 2, 3, 1]
// time complexity: O(n) for all traversals
// space complexity: O(h) where h is the height of the tree (due to recursion stack)