-
Notifications
You must be signed in to change notification settings - Fork 14
/
tree_traversal.cpp
71 lines (54 loc) · 1.2 KB
/
tree_traversal.cpp
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
#include <iostream>
using namespace std;
struct Node
{
int data;
Node *left, *right;
};
Node* newNode(int key)
{
Node *node = new Node;
node->data = key;
node->left = node->right = nullptr;
return node;
}
void preorder_traversal(Node* root)
{
if (root == nullptr)
return;
cout << root->data << " ";
preorder_traversal(root->left);
preorder_traversal(root->right);
}
void inorder_traversal(Node* root)
{
if (root == nullptr)
return;
inorder_traversal(root->left);
cout << root->data << " ";
inorder_traversal(root->right);
}
void postorder_traversal(Node* root)
{
if (root == nullptr)
return;
postorder_traversal(root->left);
postorder_traversal(root->right);
cout << root->data << " ";
}
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
cout << endl << "preorder traversal: ";
preorder_traversal(root);
cout << endl << "inorder traversal: ";
inorder_traversal(root);
cout << endl << "postorder traversal: ";
postorder_traversal(root);
cout << endl;
return 0;
}