-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary_Tree.cpp
90 lines (81 loc) · 1.81 KB
/
Binary_Tree.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/* Every node has atmost degree 2 is called binary tree
if tree has n nodes then it will have n-1 edges
Degree of node: No of direct children.
Degree of tree : highest degree of a node among all the nodes present in the tree.
Binary tree : Tree of degree two.
*/
#include <iostream>
using namespace std;
class Node
{
public:
int data;
class Node *left;
class Node *right;
};
class Node *create_Node(int data)
{
class Node *newNode = (class Node *)malloc(sizeof(class Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
/* 1 (ROOT)
2 3
left right
Three types of Traversal in Binary Tress .
PreOrder - Root/Left/Right
postOrder - Left/Right/Root
inOrder - left/Root/Right
*/
void preOrder(class Node *ptr)
{
if (ptr != NULL)
{
cout << ptr->data << "||";
preOrder(ptr->left);
preOrder(ptr->right);
}
}
void postOrder(class Node *ptr)
{
if (ptr != NULL)
{
postOrder(ptr->left);
postOrder(ptr->right);
cout << ptr->data << "||";
}
}
void inOrder(class Node *ptr)
{
if (ptr != NULL)
{
inOrder(ptr->left);
cout << ptr->data << "||";
inOrder(ptr->right);
}
}
int main()
{
class Node *p = create_Node(1);
class Node *p1 = create_Node(2);
class Node *p2 = create_Node(3);
class Node *p3 = create_Node(4);
class Node *p4 = create_Node(5);
class Node *p5 = create_Node(6);
class Node *p6 = create_Node(7);
//Linking Nodes to form a tree
p->left = p1;
p->right = p2;
p1->left = p3;
p1->right = p4;
p2->left = p5;
p2->right = p6;
preOrder(p);
cout << endl;
postOrder(p);
cout << endl;
inOrder(p);
return 0;
}