Skip to content

Commit 5d5452b

Browse files
authored
Merge pull request #637 from Paila-Sahitya/add-treeTraversals
Added recursive inorder, preorder, and postorder tree traversals
2 parents 6e55266 + 4743054 commit 5d5452b

1 file changed

Lines changed: 88 additions & 0 deletions

File tree

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
/*
5+
Algorithm: Binary Tree Traversals (Inorder, Preorder, Postorder)
6+
7+
Description:
8+
- Builds a Binary Search Tree (BST) using insertion.
9+
- Performs recursive traversals:
10+
Inorder (Left → Root → Right)
11+
Preorder (Root → Left → Right)
12+
Postorder (Left → Right → Root)
13+
- Useful for processing hierarchical data, syntax trees, and expression evaluation.
14+
15+
Time Complexity: O(n)
16+
Space Complexity: O(h), where h is tree height (O(log n) average, O(n) worst case)
17+
*/
18+
19+
class TreeNode {
20+
public:
21+
int data;
22+
TreeNode* left;
23+
TreeNode* right;
24+
25+
TreeNode(int val) {
26+
data = val;
27+
left = NULL;
28+
right = NULL;
29+
}
30+
};
31+
32+
// Function to insert a node into the BST
33+
TreeNode* insert(TreeNode* root, int val) {
34+
35+
if (!root) return new TreeNode(val);
36+
if (val < root->data) root->left = insert(root->left, val);
37+
else root->right = insert(root->right, val);
38+
return root;
39+
}
40+
41+
// Inorder traversal (Left, Root, Right)
42+
void inorder(TreeNode* root) {
43+
if (!root) return;
44+
inorder(root->left);
45+
cout << root->data << " ";
46+
inorder(root->right);
47+
}
48+
49+
//Preorder traversal (Root, Left, Right)
50+
void preorder(TreeNode* root){
51+
if(!root) return;
52+
cout<<root->data<<" ";
53+
preorder(root->left);
54+
preorder(root->right);
55+
}
56+
57+
//Postorder traversal (Left, Right, Root)
58+
void postorder(TreeNode* root){
59+
if(!root) return;
60+
postorder(root->left);
61+
postorder(root->right);
62+
cout<<root->data<<" ";
63+
}
64+
65+
66+
int main() {
67+
TreeNode* root = NULL;
68+
int n, val;
69+
70+
cout << "Enter number of nodes: ";
71+
cin >> n;
72+
73+
cout << "Enter values to insert into BST:";
74+
for (int i = 0; i < n; i++) {
75+
cin >> val;
76+
root = insert(root, val);
77+
}
78+
79+
cout << "\nInorder Traversal: ";
80+
inorder(root);
81+
cout << "\nPreorder Traversal: ";
82+
preorder(root);
83+
cout<<"\nPostorder Traversal: ";
84+
postorder(root);
85+
cout<<endl;
86+
87+
return 0;
88+
}

0 commit comments

Comments
 (0)