SlideShare a Scribd company logo
Binary Tree Traversal in Data Structure
The tree can be defined as a non-linear data structure that stores data in the form of
nodes, and nodes are connected to each other with the help of edges. Among all the
nodes, there is one main node called the root node, and all other nodes are the
children of these nodes.
In any data structure, traversal is an important operation. In the traversal operation, we
walk through the data structure visiting each element of the data structure at least
once. The traversal operation plays a very important role while doing various other
operations on the data structure like some of the operations are searching, in which
we need to visit each element of the data structure at least once so that we can
compare each incoming element from the data structure to the key that we want to
find in the data structure. So like any other data structure, the tree data also needs to
be traversed to access each element, also known as a node of the tree data structure.
There are different ways of traversing a tree depending upon the order in which the
tree's nodes are visited and the types of data structure used for traversing the tree.
There are various data structures involved in traversing a tree, as traversing a tree
involves iterating over all nodes in some manner.
As from a given node, there could be more than one way to traverse or visit the next
node of the tree, so it becomes important to store one of the nodes traverses further
and store the rest of the nodes having a possible path for backtracking the tree if
needed. Backtracking is not a linear approach, so we need different data structures for
traversing through the whole tree. The stack and queue are the major data structure
that is used for traversing a tree.
Traversal is a technique for visiting all of a tree's nodes and printing their values.
Traversing a tree involves iterating over all nodes in some manner. We always start
from the root (head) node since all nodes are connected by edges (links). As the tree
is not a linear data structure, there can be more than one possible next node from a
given node, so some nodes must be deferred, i.e., stored in some way for later visiting.
Implicit Array Representation of Binary Trees
A binary tree can be represented using a linked list and also using an array. Representation of
this tree, using both(array and linked list) is explained below.
In the implicit array representation of binary trees, you use a one-dimensional array
to represent a binary tree without using explicit pointers. The idea is to map the
elements of the array to the nodes of the binary tree in a way that allows you to
navigate through the tree efficiently.
Here's an example in C programming for creating and traversing a binary tree using
an implicit array representation:
#include <stdio.h>
// Function to perform in-order traversal of the implicit array representation
void inOrderTraversal(int arr[], int n, int index) {
if (index < n) {
// Recur on the left subtree
inOrderTraversal(arr, n, 2 * index + 1);
// Process the current node
printf("%d ", arr[index]);
// Recur on the right subtree
inOrderTraversal(arr, n, 2 * index + 2);
}
}
int main() {
// Example implicit array representing a binary tree
int arr[] = {1, 2, 3, 4, 5, 6, 7};
// Get the number of elements in the array
int n = sizeof(arr) / sizeof(arr[0]);
// Perform in-order traversal
printf("In-order traversal: ");
inOrderTraversal(arr, n, 0);
printf("n");
return 0;
}
In this example, the implicit array is filled with elements such that if an element is at
index i in the array, its left child is at index 2*i + 1 and its right child is at index 2*i +
2. This arrangement allows you to navigate through the binary tree without using
explicit pointers.
The inOrderTraversal function performs an in-order traversal of the binary tree
represented by the implicit array. You can adapt this approach for other types of tree
traversals (pre-order, post-order, etc.) based on your requirements. Keep in mind that
this method assumes a complete binary tree for simplicity. In a real-world scenario,
you might need additional techniques to handle incomplete binary trees.
Types of Traversal of Binary Tree
There are three types of traversal of a binary tree.
1. Inorder tree traversal
2. Preorder tree traversal
3. Postorder tree traversal
Inorder Tree Traversal
The left subtree is visited first, followed by the root, and finally the right subtree in this
traversal strategy. Always keep in mind that any node might be a subtree in and of
itself. The output of a binary tree traversal in order produces sorted key values in
ascending order.
C Code
Let's write a basic C program for Inorder traversal of the binary search tree.
1. //C Program for Inorder traversal of the binary search tree
2.
3. #include<stdio.h>
4. #include<stdlib.h>
5.
6. struct node
7. {
8. int key;
9. struct node *left;
10. struct node *right;
11. };
12.
13. //return a new node with the given value
14. struct node *getNode(int val)
15. {
16. struct node *newNode;
17.
18. newNode = malloc(sizeof(struct node));
19.
20. newNode->key = val;
21. newNode->left = NULL;
22. newNode->right = NULL;
23.
24. return newNode;
25. }
26.
27. //inserts nodes in the binary search tree
28. struct node *insertNode(struct node *root, int val)
29. {
30. if(root == NULL)
31. return getNode(val);
32.
33. if(root->key < val)
34. root->right = insertNode(root->right,val);
35.
36. if(root->key > val)
37. root->left = insertNode(root->left,val);
38.
39. return root;
40. }
41.
42. //inorder traversal of the binary search tree
43. void inorder(struct node *root)
44. {
45. if(root == NULL)
46. return;
47.
48. //traverse the left subtree
49. inorder(root->left);
50.
51. //visit the root
52. printf("%d ",root->key);
53.
54. //traverse the right subtree
55. inorder(root->right);
56. }
57.
58. int main()
59. {
60. struct node *root = NULL;
61.
62.
63. int data;
64. char ch;
65. /* Do while loop to display various options to select from to decide the i
nput */
66. do
67. {
68. printf("nSelect one of the operations::");
69. printf("n1. To insert a new node in the Binary Tree");
70. printf("n2. To display the nodes of the Binary Tree(via Inorder Traversal).n");
71.
72. int choice;
73. scanf("%d",&choice);
74. switch (choice)
75. {
76. case 1 :
77. printf("nEnter the value to be insertedn");
78. scanf("%d",&data);
79. root = insertNode(root,data);
80. break;
81. case 2 :
82. printf("nInorder Traversal of the Binary Tree::n");
83. inorder(root);
84. break;
85. default :
86. printf("Wrong Entryn");
87. break;
88. }
89.
90. printf("nDo you want to continue (Type y or n)n");
91. scanf(" %c",&ch);
92. } while (ch == 'Y'|| ch == 'y');
93.
94. return 0;
95. }
Output
The above C code hives the following output.
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree (via Inorder Traversal).
1
Enter the value to be inserted
12
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Inorder Traversal).
1
Enter the value to be inserted
98
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Inorder Traversal).
1
Enter the value to be inserted
23
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Inorder Traversal).
1
Enter the value to be inserted
78
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Inorder Traversal).
1
Enter the value to be inserted
45
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Inorder Traversal).
1
Enter the value to be inserted
87
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Inorder Traversal).
2
Inorder Traversal of the Binary Tree::
12 23 45 78 87 98
Do you want to continue (Type y or n)
n
Preorder Tree Traversal
In this traversal method, the root node is visited first, then the left subtree, and finally
the right subtree.
Code
Let's write a C code for the Preorder traversal of the binary search tree.
1. /*
2. * Program: Preorder traversal of the binary search tree
3. * Language: C
4. */
5.
6. #include<stdio.h>
7. #include<stdlib.h>
8.
9. struct node
10. {
11. int key;
12. struct node *left;
13. struct node *right;
14. };
15.
16. //return a new node with the given value
17. struct node *getNode(int val)
18. {
19. struct node *newNode;
20.
21. newNode = malloc(sizeof(struct node));
22.
23. newNode->key = val;
24. newNode->left = NULL;
25. newNode->right = NULL;
26.
27. return newNode;
28. }
29.
30. //inserts nodes in the binary search tree
31. struct node *insertNode(struct node *root, int val)
32. {
33. if(root == NULL)
34. return getNode(val);
35.
36. if(root->key < val)
37. root->right = insertNode(root->right,val);
38.
39. if(root->key > val)
40. root->left = insertNode(root->left,val);
41.
42. return root;
43. }
44.
45. //preorder traversal of the binary search tree
46. void preorder(struct node *root)
47. {
48. if(root == NULL)
49. return;
50.
51. //visit the root
52. printf("%d ",root->key);
53.
54. //traverse the left subtree
55. preorder(root->left);
56.
57. //traverse the right subtree
58. preorder(root->right);
59. }
60.
61. int main()
62. {
63. struct node *root = NULL;
64.
65. int data;
66. char ch;
67. /* Do while loop to display various options to select from to decide the i
nput */
68. do
69. {
70. printf("nSelect one of the operations::");
71. printf("n1. To insert a new node in the Binary Tree");
72. printf("n2. To display the nodes of the Binary Tree(via Preorder Traversal).n");
73.
74. int choice;
75. scanf("%d",&choice);
76. switch (choice)
77. {
78. case 1 :
79. printf("nEnter the value to be insertedn");
80. scanf("%d",&data);
81. root = insertNode(root,data);
82. break;
83. case 2 :
84. printf("nPreorder Traversal of the Binary Tree::n");
85. preorder(root);
86. break;
87. default :
88. printf("Wrong Entryn");
89. break;
90. }
91.
92. printf("nDo you want to continue (Type y or n)n");
93. scanf(" %c",&ch);
94. } while (ch == 'Y'|| ch == 'y');
95.
96. return 0;
97. }
Output:
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Preorder Traversal).
1
Enter the value to be inserted
45
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Preorder Traversal).
1
Enter the value to be inserted
53
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Preorder Traversal).
1
Enter the value to be inserted
1
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Preorder Traversal).
1
Enter the value to be inserted
2
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Preorder Traversal).
1
Enter the value to be inserted
97
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Preorder Traversal).
1
Enter the value to be inserted
22
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Preorder Traversal).
2
Preorder Traversal of the Binary Tree::
45 1 2 22 53 97
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Preorder Traversal).
1
Enter the value to be inserted
76
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Preorder Traversal).
1
Enter the value to be inserted
30
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Preorder Traversal).
1
Enter the value to be inserted
67
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Preorder Traversal).
1
Enter the value to be inserted
4
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Preorder Traversal).
2
Preorder Traversal of the Binary Tree::
45 1 2 22 4 30 53 97 76 67
Do you want to continue (Type y or n)
n
Postorder Tree Traversal
The root node is visited last in this traversal method, hence the name. First, we traverse
the left subtree, then the right subtree, and finally the root node.
Code
Let's write a program for Postorder traversal of the binary search tree.
1. /*
2. * Program: Postorder traversal of the binary search tree
3. * Language: C
4. */
5.
6. #include<stdio.h>
7. #include<stdlib.h>
8.
9. struct node
10. {
11. int key;
12. struct node *left;
13. struct node *right;
14. };
15.
16. //return a new node with the given value
17. struct node *getNode(int val)
18. {
19. struct node *newNode;
20.
21. newNode = malloc(sizeof(struct node));
22.
23. newNode->key = val;
24. newNode->left = NULL;
25. newNode->right = NULL;
26.
27. return newNode;
28. }
29. //inserts nodes in the binary search tree
30. struct node *insertNode(struct node *root, int val)
31. {
32. if(root == NULL)
33. return getNode(val);
34.
35. if(root->key < val)
36. root->right = insertNode(root->right,val);
37.
38. if(root->key > val)
39. root->left = insertNode(root->left,val);
40.
41. return root;
42. }
43.
44. //postorder traversal of the binary search tree
45. void postorder(struct node *root)
46. {
47. if(root == NULL)
48. return;
49.
50. //traverse the left subtree
51. postorder(root->left);
52.
53. //traverse the right subtree
54. postorder(root->right);
55.
56. //visit the root
57. printf("%d ",root->key);
58. }
59. int main()
60. {
61. struct node *root = NULL;
62.
63.
64. int data;
65. char ch;
66. /* Do while loop to display various options to select from to decide the input */
67. do
68. {
69. printf("nSelect one of the operations::");
70. printf("n1. To insert a new node in the Binary Tree");
71. printf("n2. To display the nodes of the Binary Tree(via Postorder Trave
rsal).n");
72.
73. int choice;
74. scanf("%d",&choice);
75. switch (choice)
76. {
77. case 1 :
78. printf("nEnter the value to be insertedn");
79. scanf("%d",&data);
80. root = insertNode(root,data);
81. break;
82. case 2 :
83. printf("nPostorder Traversal of the Binary Tree::n");
84. postorder(root);
85. break;
86. default :
87. printf("Wrong Entryn");
88. break;
89. }
90.
91. printf("nDo you want to continue (Type y or n)n");
92. scanf(" %c",&ch);
93. } while (ch == 'Y'|| ch == 'y');
94.
95. return 0;
96. }
Output:
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Postorder Traversal).
1
Enter the value to be inserted
12
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Postorder Traversal).
1
Enter the value to be inserted
31
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Postorder Traversal).
24
Wrong Entry
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Postorder Traversal).
1
Enter the value to be inserted
24
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Postorder Traversal).
1
Enter the value to be inserted
88
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Postorder Traversal).
1
Enter the value to be inserted
67
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Postorder Traversal).
1
Enter the value to be inserted
56
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Postorder Traversal).
1
Enter the value to be inserted
90
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Postorder Traversal).
1
Enter the value to be inserted
44
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Postorder Traversal).
1
Enter the value to be inserted
71
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Postorder Traversal).
1
Enter the value to be inserted
38
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Postorder Traversal).
1
Enter the value to be inserted
29
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Postorder Traversal).
2
Postorder Traversal of the Binary Tree::
29 24 38 44 56 71 67 90 88 31 12
Do you want to continue (Type y or n)
n
We have seen the different C programs to implement inorder, preorder, and postorder
traversal of the nodes of the Binary tree. Now let us write a code to perform all three
types of traversal in a single program.
Code
1. //Binary tree traversal:
2.
3. #include <stdio.h>
4. // #include <conio.h>
5. #include <malloc.h>
6. struct node
7. {
8. struct node *left;
9. int data;
10. struct node *right;
11. };
12.
13. void main()
14. {
15. void insert(struct node **,int);
16. void inorder(struct node *);
17. void postorder(struct node *);
18. void preorder(struct node *);
19.
20. struct node *ptr = NULL;
21. int no,i,num;
22.
23. // ptr = NULL;
24. // ptr->data=0;
25.
26. int data;
27. char ch;
28. /* Do while loop to display various options to select from to decide the input */
29. do
30. {
31. printf("nSelect one of the operations::");
32. printf("n1. To insert a new node in the Binary Tree");
33. printf("n2. To display the nodes of the Binary Tree(via Preorder Travers
al).");
34. printf("n3. To display the nodes of the Binary Tree(via Inorder Traversal).");
35. printf("n4. To display the nodes of the Binary Tree(via Postorder Trave
rsal).n");
36.
37. int choice;
38. scanf("%d",&choice);
39. switch (choice)
40. {
41. case 1 :
42. printf("nEnter the value to be insertedn");
43. scanf("%d",&data);
44. insert(&ptr,data);
45. break;
46. case 2 :
47. printf("nPreorder Traversal of the Binary Tree::n");
48. preorder(ptr);
49. break;
50. case 3 :
51. printf("nInorder Traversal of the Binary Tree::n");
52. inorder(ptr);
53. break;
54. case 4 :
55. printf("nPostorder Traversal of the Binary Tree::n");
56. postorder(ptr);
57. break;
58. default :
59. printf("Wrong Entryn");
60. break;
61. }
62.
63. printf("nDo you want to continue (Type y or n)n");
64. scanf(" %c",&ch);
65. } while (ch == 'Y'|| ch == 'y');
66.
67.
68. // printf("nProgram for Tree Traversaln");
69. // printf("Enter the number of nodes to add to the tree.<BR>n");
70. // scanf("%d",&no);
71.
72. // for(i=0;i<no;i++)
73. // {
74. // printf("Enter the itemn");
75. // scanf("%d",&num);
76. // insert(&ptr,num);
77. // }
78.
79. // //getch();
80. // printf("nINORDER TRAVERSALn");
81. // inorder(ptr);
82.
83. // printf("nPREORDER TRAVERSALn");
84. // preorder(ptr);
85.
86. // printf("nPOSTORDER TRAVERSALn");
87. // postorder(ptr);
88.
89. }
90.
91. void insert(struct node **p,int num)
92. {
93. if((*p)==NULL)
94. {
95. printf("Leaf node created.");
96. (*p)=malloc(sizeof(struct node));
97. (*p)->left = NULL;
98. (*p)->right = NULL;
99. (*p)->data = num;
100. return;
101. }
102. else
103. {
104. if(num==(*p)->data)
105. {
106. printf("nREPEATED ENTRY ERROR VALUE REJECTEDn");
107. return;
108. }
109. if(num<(*p)->data)
110. {
111. printf("nDirected to left link.n");
112. insert(&((*p)->left),num);
113. }
114. else
115. {
116. printf("Directed to right link.n");
117. insert(&((*p)->right),num);
118. }
119. }
120. return;
121. }
122.
123. void inorder(struct node *p)
124. {
125. if(p!=NULL)
126. {
127. inorder(p->left);
128. printf("%d ",p->data);
129. inorder(p->right);
130. }
131. else
132. return;
133. }
134.
135. void preorder(struct node *p)
136. {
137. if(p!=NULL)
138. {
139. printf("%d ",p->data);
140. preorder(p->left);
141. preorder(p->right);
142. }
143. else
144. return;
145. }
146.
147. void postorder(struct node *p)
148. {
149. if(p!=NULL)
150. {
151. postorder(p->left);
152. postorder(p->right);
153. printf("%d ",p->data);
154. }
155. else
156. return;
157. }
Output:
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Preorder Traversal).
3. To display the nodes of the Binary Tree(via Inorder Traversal).
4. To display the nodes of the Binary Tree(via Postorder Traversal).
1
Enter the value to be inserted
2
Leaf node created.
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Preorder Traversal).
3. To display the nodes of the Binary Tree(via Inorder Traversal).
4. To display the nodes of the Binary Tree(via Postorder Traversal).
1
Enter the value to be inserted
5
Directed to right link.
Leaf node created.
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Preorder Traversal).
3. To display the nodes of the Binary Tree(via Inorder Traversal).
4. To display the nodes of the Binary Tree(via Postorder Traversal).
1
Enter the value to be inserted
7
Directed to right link.
Directed to right link.
Leaf node created.
Do you want to continue (Type y or n)
Y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Preorder Traversal).
3. To display the nodes of the Binary Tree(via Inorder Traversal).
4. To display the nodes of the Binary Tree(via Postorder Traversal).
1
Enter the value to be inserted
9
Directed to right link.
Directed to right link.
Directed to right link.
Leaf node created.
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Preorder Traversal).
3. To display the nodes of the Binary Tree(via Inorder Traversal).
4. To display the nodes of the Binary Tree(via Postorder Traversal).
1
Enter the value to be inserted
31
Directed to right link.
Directed to right link.
Directed to right link.
Directed to right link.
Leaf node created.
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Preorder Traversal).
3. To display the nodes of the Binary Tree(via Inorder Traversal).
4. To display the nodes of the Binary Tree(via Postorder Traversal).
1
Enter the value to be inserted
78
Directed to right link.
Directed to right link.
Directed to right link.
Directed to right link.
Directed to right link.
Leaf node created.
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Preorder Traversal).
3. To display the nodes of the Binary Tree(via Inorder Traversal).
4. To display the nodes of the Binary Tree(via Postorder Traversal).
2
Preorder Traversal of the Binary Tree::
2 5 7 9 31 78
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Preorder Traversal).
3. To display the nodes of the Binary Tree(via Inorder Traversal).
4. To display the nodes of the Binary Tree(via Postorder Traversal).
3
Inorder Traversal of the Binary Tree::
2 5 7 9 31 78
Do you want to continue (Type y or n)
y
Select one of the operations::
1. To insert a new node in the Binary Tree
2. To display the nodes of the Binary Tree(via Preorder Traversal).
3. To display the nodes of the Binary Tree(via Inorder Traversal).
4. To display the nodes of the Binary Tree(via Postorder Traversal).
4
Postorder Traversal of the Binary Tree::
78 31 9 7 5 2
Do you want to continue (Type y or n)
n
Threaded Binary Tree
In this article, we will understand about the threaded binary tree in detail.
What do you mean by Threaded Binary Tree?
In the linked representation of binary trees, more than one half of the link fields contain
NULL values which results in wastage of storage space. If a binary tree consists
of n nodes then n+1 link fields contain NULL values. So in order to effectively manage
the space, a method was devised by Perlis and Thornton in which the NULL links are
replaced with special links known as threads. Such binary trees with threads are known
as threaded binary trees. Each node in a threaded binary tree either contains a link
to its child node or thread to other nodes in the tree.
Types of Threaded Binary Tree
There are two types of threaded Binary Tree:
o One-way threaded Binary Tree
o Two-way threaded Binary Tree
One-way threaded Binary trees:
In one-way threaded binary trees, a thread will appear either in the right or left link
field of a node. If it appears in the right link field of a node then it will point to the next
node that will appear on performing in order traversal. Such trees are called Right
threaded binary trees. If thread appears in the left field of a node then it will point to
the nodes inorder predecessor. Such trees are called Left threaded binary trees. Left
threaded binary trees are used less often as they don't yield the last advantages of
right threaded binary trees. In one-way threaded binary trees, the right link field of last
node and left link field of first node contains a NULL. In order to distinguish threads
from normal links they are represented by dotted lines.
The above figure shows the inorder traversal of this binary tree yields D, B, E, A, C, F.
When this tree is represented as a right threaded binary tree, the right link field of leaf
node D which contains a NULL value is replaced with a thread that points to node B
which is the inorder successor of a node D. In the same way other nodes containing
values in the right link field will contain NULL value.
Two-way threaded Binary Trees:
In two-way threaded Binary trees, the right link field of a node containing NULL values
is replaced by a thread that points to nodes inorder successor and left field of a node
containing NULL values is replaced by a thread that points to nodes inorder
predecessor.
ADVERTISEMENT
The above figure shows the inorder traversal of this binary tree yields D, B, E, G, A, C,
F. If we consider the two-way threaded Binary tree, the node E whose left field contains
NULL is replaced by a thread pointing to its inorder predecessor i.e. node B. Similarly,
for node G whose right and left linked fields contain NULL values are replaced by
threads such that right link field points to its inorder successor and left link field points
to its inorder predecessor. In the same way, other nodes containing NULL values in
their link fields are filled with threads.
ADVERTISEMENT
In the above figure of two-way threaded Binary tree, we noticed that no left thread is
possible for the first node and no right thread is possible for the last node. This is
because they don't have any inorder predecessor and successor respectively. This is
indicated by threads pointing nowhere. So in order to maintain the uniformity of
threads, we maintain a special node called the header node. The header node does
not contain any data part and its left link field points to the root node and its right link
field points to itself. If this header node is included in the two-way threaded Binary
tree then this node becomes the inorder predecessor of the first node and inorder
successor of the last node. Now threads of left link fields of the first node and right
link fields of the last node will point to the header node.
Algorithm for Inorder Traversal of Threaded Binary
Tree:
1. ALgorithm Inorder(I)
2. {
3. ThreadedTreeNode *Header;
4. Header=I;
5. while(1)
6. {
7. I=fnFindInorder_Successor(H);
8. if(I==Header)
9. return;
10. else
11. print(I->info);
12. }
13. }
14. In the above algorithm, we have discussed the Inorder traversal of Threaded bi
nary trees.
15. Pseudocode of Threaded Tree in C:
16. #include <stdio.h>
17. #include <stdlib.h>
18. typedef enum {false,true} boolean;
19. struct node *in_succ(struct node *p);
20. struct node *in_pred(struct node *p);
21. struct node *insert(struct node *root, int ikey);
22. struct node *del(struct node *root, int dkey);
23. struct node *case_a(struct node *root, struct node *par,struct node *ptr);
24. struct node *case_b(struct node *root,struct node *par,struct node *ptr);
25. struct node *case_c(struct node *root, struct node *par,struct node *ptr);
26. void inorder( struct node *root);
27. void preorder( struct node *root);
28.
29. struct node
30. {
31. struct node *left;
32. boolean lthread;
33. int info;
34. boolean rthread;
35. struct node *right;
36. };
37. int main( )
38. {
39. clrscr();
40. int choice,num;
41. struct node *root=NULL;
42. while(1)
43. {
44. printf("Program of Threaded Tree in Cn");
45. printf("1.Insertn");
46. printf("2.Deleten");
47. printf("3.Inorder Traversaln");
48. printf("4.Preorder Traversaln");
49. printf("5.Quitn");
50. printf("nEnter your choice : ");
51. scanf("%d",&choice);
52. switch(choice)
53. {
54. case 1:
55. printf("nEnter the number to be inserted : ");
56. scanf("%d",&num);
57. root = insert(root,num);
58. break;
59. case 2:
60. printf("nEnter the number to be deleted : ");
61. scanf("%d",&num);
62. root = del(root,num);
63. break;
64. case 3:
65. inorder(root);
66. break;
67. case 4:
68. preorder(root);
69. break;
70. case 5:
71. exit(1);
72.
73. default:
74. printf("nWrong choicen");
75. }
76. }
77. return 0;
78. }
79. struct node *insert(struct node *root, int ikey)
80. {
81. struct node *tmp,*par,*ptr;
82. int found=0;
83. ptr = root;
84. par = NULL;
85. while( ptr!=NULL )
86. {
87. if( ikey == ptr->info)
88. {
89. found =1;
90. break;
91. }
92. par = ptr;
93. if(ikey < ptr->info)
94. {
95. if(ptr->lthread == false)
96. ptr = ptr->left;
97. else
98. break;
99. }
100. else
101. {
102. if(ptr->rthread == false)
103. ptr = ptr->right;
104. else
105. break;
106. }
107. }
108. if(found)
109. printf("nDuplicate key");
110. else
111. {
112. tmp=(struct node *)malloc(sizeof(struct node));
113. tmp->info=ikey;
114. tmp->lthread = true;
115. tmp->rthread = true;
116. if(par==NULL)
117. {
118. root=tmp;
119. tmp->left=NULL;
120. tmp->right=NULL;
121. }
122. else if( ikey < par->info )
123. {
124. tmp->left=par->left;
125. tmp->right=par;
126. par->lthread=false;
127. par->left=tmp;
128. }
129. else
130. {
131. tmp->left=par;
132. tmp->right=par->right;
133. par->rthread=false;
134. par->right=tmp;
135. }
136. }
137. return root;
138. }
139.
140. struct node *del(struct node *root, int dkey)
141. {
142. struct node *par,*ptr;
143. int found=0;
144. ptr = root;
145. par = NULL;
146. while( ptr!=NULL)
147. {
148. if( dkey == ptr->info)
149. {
150. found =1;
151. break;
152. }
153. par = ptr;
154. if(dkey < ptr->info)
155. {
156. if(ptr->lthread == false)
157. ptr = ptr->left;
158. else
159. break;
160. }
161. else
162. {
163. if(ptr->rthread == false)
164. ptr = ptr->right;
165. else
166. break;
167. }
168. }
169. if(found==0)
170. printf("ndkey not present in tree");
171. else if(ptr->lthread==false && ptr->rthread==false)/*2 children*/
172. root = case_c(root,par,ptr);
173. else if(ptr->lthread==false )
174. root = case_b(root, par,ptr);
175. else if(ptr->rthread==false)
176. root = case_b(root, par,ptr);
177. else
178. root = case_a(root,par,ptr);
179. return root;
180. }
181.
182. struct node *case_a(struct node *root, struct node *par,struct node *ptr
)
183. {
184. if(par==NULL)
185. root=NULL;
186. else if(ptr==par->left)
187. {
188. par->lthread=true;
189. par->left=ptr->left;
190. }
191. else
192. {
193. par->rthread=true;
194. par->right=ptr->right;
195. }
196. free(ptr);
197. return root;
198. }
199. struct node *case_b(struct node *root,struct node *par,struct node *ptr)
200. {
201. struct node *child,*s,*p;
202. if(ptr->lthread==false)
203. child=ptr->left;
204. else
205. child=ptr->right;
206. if(par==NULL )
207. root=child;
208. else if( ptr==par->left)
209. par->left=child;
210. else
211. par->right=child;
212. s=in_succ(ptr);
213. p=in_pred(ptr);
214. if(ptr->lthread==false)
215. p->right=s;
216. else
217. {
218. if(ptr->rthread==false)
219. s->left=p;
220. }
221. free(ptr);
222. return root;
223. }
224. struct node *case_c(struct node *root, struct node *par,struct node *ptr)
225. {
226. struct node *succ,*parsucc;
227. parsucc = ptr;
228. succ = ptr->right;
229. while(succ->left!=NULL)
230. {
231. parsucc = succ;
232. succ = succ->left;
233. }
234. ptr->info = succ->info;
235. if(succ->lthread==true && succ->rthread==true)
236. root = case_a(root, parsucc,succ);
237. else
238. root = case_b(root, parsucc,succ);
239. return root;
240. }
241. struct node *in_succ(struct node *ptr)
242. {
243. if(ptr->rthread==true)
244. return ptr->right;
245. else
246. {
247. ptr=ptr->right;
248. while(ptr->lthread==false)
249. ptr=ptr->left;
250. return ptr;
251. }
252. }
253. struct node *in_pred(struct node *ptr)
254. {
255. if(ptr->lthread==true)
256. return ptr->left;
257. else
258. {
259. ptr=ptr->left;
260. while(ptr->rthread==false)
261. ptr=ptr->right;
262. return ptr;
263. }
264. }
265. void inorder( struct node *root)
266. {
267. struct node *ptr;
268. if(root == NULL )
269. {
270. printf("Tree is empty");
271. return;
272. }
273. ptr=root;
274. while(ptr->lthread==false)
275. ptr=ptr->left;
276. while( ptr!=NULL )
277. {
278. printf("%d ",ptr->info);
279. ptr=in_succ(ptr);
280. }
281. }
282. void preorder(struct node *root )
283. {
284. struct node *ptr;
285. if(root==NULL)
286. {
287. printf("Tree is empty");
288. return;
289. }
290. ptr=root;
291. while(ptr!=NULL)
292. {
293. printf("%d ",ptr->info);
294. if(ptr->lthread==false)
295. ptr=ptr->left;
296. else if(ptr->rthread==false)
297. ptr=ptr->right;
298. else
299. {
300. while(ptr!=NULL && ptr->rthread==true)
301. ptr=ptr->right;
302. if(ptr!=NULL)
303. ptr=ptr->right;
304. }
305. }
306. }
Explanation:
In the above example, we have created a threaded binary tree for various operations.
Output:
DS UNIT5_BINARY TREES.docx
Advantages of Threaded Binary Tree:
o In threaded binary tree, linear and fast traversal of nodes in the tree so there is
no requirement of stack. If the stack is used then it consumes a lot of memory
and time.
o It is more general as one can efficiently determine the successor and
predecessor of any node by simply following the thread and links. It almost
behaves like a circular linked list.
Disadvantages of Threaded Binary Tree:
o When implemented, the threaded binary tree needs to maintain the extra
information for each node to indicate whether the link field of each node points
to an ordinary node or the node's successor and predecessor.
o Insertion into and deletion from a threaded binary tree are more time
consuming since both threads and ordinary links need to be maintained.

More Related Content

Similar to DS UNIT5_BINARY TREES.docx (20)

PDF
Binary trees
Ssankett Negi
 
DOCX
Running Head Discussion Board .docx
jeanettehully
 
PPTX
linkedlist.pptx
MeghaKulkarni27
 
PDF
Given a newly created Binary Search Tree with the following numerica.pdf
hadpadrrajeshh
 
DOCX
611+tutorial
Prudence Mashile
 
DOCX
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docx
festockton
 
PPTX
C Exam Help
Programming Exam Help
 
PDF
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
info114
 
DOCX
#include iostream using namespace std; const int nil = 0; cl.docx
ajoy21
 
PDF
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
vishalateen
 
PDF
Please write in C++ and should be able to compile and debug.Thank yo.pdf
ajaycosmeticslg
 
PDF
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
stopgolook
 
PDF
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Balwant Gorad
 
PPTX
UNIT 3a.pptx
jack881
 
PDF
Introduction---to-Expression---Trees.pdf
khetyidris
 
PPT
Funddamentals of data structures
Globalidiots
 
PPTX
Linked list
Md. Afif Al Mamun
 
PDF
Linked list
somuinfo123
 
DOCX
IIT Hyd exam preps.docx
AdraVasi
 
PPTX
Data structure
Nida Ahmed
 
Binary trees
Ssankett Negi
 
Running Head Discussion Board .docx
jeanettehully
 
linkedlist.pptx
MeghaKulkarni27
 
Given a newly created Binary Search Tree with the following numerica.pdf
hadpadrrajeshh
 
611+tutorial
Prudence Mashile
 
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docx
festockton
 
C Exam Help
Programming Exam Help
 
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
info114
 
#include iostream using namespace std; const int nil = 0; cl.docx
ajoy21
 
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
vishalateen
 
Please write in C++ and should be able to compile and debug.Thank yo.pdf
ajaycosmeticslg
 
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
stopgolook
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Balwant Gorad
 
UNIT 3a.pptx
jack881
 
Introduction---to-Expression---Trees.pdf
khetyidris
 
Funddamentals of data structures
Globalidiots
 
Linked list
Md. Afif Al Mamun
 
Linked list
somuinfo123
 
IIT Hyd exam preps.docx
AdraVasi
 
Data structure
Nida Ahmed
 

More from VeerannaKotagi1 (8)

PPTX
MODULE_3_Methods and Classes Overloading.pptx
VeerannaKotagi1
 
PPTX
MODULE_2_Operators.pptx
VeerannaKotagi1
 
PPTX
MODULE_1_The History and Evolution of Java.pptx
VeerannaKotagi1
 
DOCX
MODULE5_EXCEPTION HANDLING.docx
VeerannaKotagi1
 
DOCX
DS UNIT4_OTHER LIST STRUCTURES.docx
VeerannaKotagi1
 
PPTX
DS UNIT2QUEUES.pptx
VeerannaKotagi1
 
PPTX
DS UNIT1_STACKS.pptx
VeerannaKotagi1
 
DOCX
DS UNIT3_LINKED LISTS.docx
VeerannaKotagi1
 
MODULE_3_Methods and Classes Overloading.pptx
VeerannaKotagi1
 
MODULE_2_Operators.pptx
VeerannaKotagi1
 
MODULE_1_The History and Evolution of Java.pptx
VeerannaKotagi1
 
MODULE5_EXCEPTION HANDLING.docx
VeerannaKotagi1
 
DS UNIT4_OTHER LIST STRUCTURES.docx
VeerannaKotagi1
 
DS UNIT2QUEUES.pptx
VeerannaKotagi1
 
DS UNIT1_STACKS.pptx
VeerannaKotagi1
 
DS UNIT3_LINKED LISTS.docx
VeerannaKotagi1
 
Ad

Recently uploaded (20)

PDF
GTU Civil Engineering All Semester Syllabus.pdf
Vimal Bhojani
 
PDF
monopile foundation seminar topic for civil engineering students
Ahina5
 
PPTX
UNIT DAA PPT cover all topics 2021 regulation
archu26
 
PPTX
Snet+Pro+Service+Software_SNET+Pro+2+Instructions.pptx
jenilsatikuvar1
 
PPTX
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
PPTX
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
PPTX
Element 7. CHEMICAL AND BIOLOGICAL AGENT.pptx
merrandomohandas
 
PDF
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
PDF
Zilliz Cloud Demo for performance and scale
Zilliz
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PPTX
Green Building & Energy Conservation ppt
Sagar Sarangi
 
DOCX
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
PPTX
Hashing Introduction , hash functions and techniques
sailajam21
 
PPTX
Server Side Web Development Unit 1 of Nodejs.pptx
sneha852132
 
PDF
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
PDF
6th International Conference on Machine Learning Techniques and Data Science ...
ijistjournal
 
PDF
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
PDF
Design Thinking basics for Engineers.pdf
CMR University
 
PPTX
GitOps_Repo_Structure for begeinner(Scaffolindg)
DanialHabibi2
 
PPTX
artificial intelligence applications in Geomatics
NawrasShatnawi1
 
GTU Civil Engineering All Semester Syllabus.pdf
Vimal Bhojani
 
monopile foundation seminar topic for civil engineering students
Ahina5
 
UNIT DAA PPT cover all topics 2021 regulation
archu26
 
Snet+Pro+Service+Software_SNET+Pro+2+Instructions.pptx
jenilsatikuvar1
 
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
Element 7. CHEMICAL AND BIOLOGICAL AGENT.pptx
merrandomohandas
 
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
Zilliz Cloud Demo for performance and scale
Zilliz
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
Green Building & Energy Conservation ppt
Sagar Sarangi
 
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
Hashing Introduction , hash functions and techniques
sailajam21
 
Server Side Web Development Unit 1 of Nodejs.pptx
sneha852132
 
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
6th International Conference on Machine Learning Techniques and Data Science ...
ijistjournal
 
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
Design Thinking basics for Engineers.pdf
CMR University
 
GitOps_Repo_Structure for begeinner(Scaffolindg)
DanialHabibi2
 
artificial intelligence applications in Geomatics
NawrasShatnawi1
 
Ad

DS UNIT5_BINARY TREES.docx

  • 1. Binary Tree Traversal in Data Structure The tree can be defined as a non-linear data structure that stores data in the form of nodes, and nodes are connected to each other with the help of edges. Among all the nodes, there is one main node called the root node, and all other nodes are the children of these nodes. In any data structure, traversal is an important operation. In the traversal operation, we walk through the data structure visiting each element of the data structure at least once. The traversal operation plays a very important role while doing various other operations on the data structure like some of the operations are searching, in which we need to visit each element of the data structure at least once so that we can compare each incoming element from the data structure to the key that we want to find in the data structure. So like any other data structure, the tree data also needs to be traversed to access each element, also known as a node of the tree data structure. There are different ways of traversing a tree depending upon the order in which the tree's nodes are visited and the types of data structure used for traversing the tree. There are various data structures involved in traversing a tree, as traversing a tree involves iterating over all nodes in some manner. As from a given node, there could be more than one way to traverse or visit the next node of the tree, so it becomes important to store one of the nodes traverses further and store the rest of the nodes having a possible path for backtracking the tree if needed. Backtracking is not a linear approach, so we need different data structures for traversing through the whole tree. The stack and queue are the major data structure that is used for traversing a tree. Traversal is a technique for visiting all of a tree's nodes and printing their values. Traversing a tree involves iterating over all nodes in some manner. We always start from the root (head) node since all nodes are connected by edges (links). As the tree is not a linear data structure, there can be more than one possible next node from a given node, so some nodes must be deferred, i.e., stored in some way for later visiting. Implicit Array Representation of Binary Trees A binary tree can be represented using a linked list and also using an array. Representation of this tree, using both(array and linked list) is explained below.
  • 2. In the implicit array representation of binary trees, you use a one-dimensional array to represent a binary tree without using explicit pointers. The idea is to map the elements of the array to the nodes of the binary tree in a way that allows you to navigate through the tree efficiently.
  • 3. Here's an example in C programming for creating and traversing a binary tree using an implicit array representation: #include <stdio.h> // Function to perform in-order traversal of the implicit array representation void inOrderTraversal(int arr[], int n, int index) { if (index < n) { // Recur on the left subtree inOrderTraversal(arr, n, 2 * index + 1); // Process the current node printf("%d ", arr[index]); // Recur on the right subtree inOrderTraversal(arr, n, 2 * index + 2); } } int main() { // Example implicit array representing a binary tree int arr[] = {1, 2, 3, 4, 5, 6, 7}; // Get the number of elements in the array int n = sizeof(arr) / sizeof(arr[0]);
  • 4. // Perform in-order traversal printf("In-order traversal: "); inOrderTraversal(arr, n, 0); printf("n"); return 0; } In this example, the implicit array is filled with elements such that if an element is at index i in the array, its left child is at index 2*i + 1 and its right child is at index 2*i + 2. This arrangement allows you to navigate through the binary tree without using explicit pointers. The inOrderTraversal function performs an in-order traversal of the binary tree represented by the implicit array. You can adapt this approach for other types of tree traversals (pre-order, post-order, etc.) based on your requirements. Keep in mind that this method assumes a complete binary tree for simplicity. In a real-world scenario, you might need additional techniques to handle incomplete binary trees. Types of Traversal of Binary Tree There are three types of traversal of a binary tree. 1. Inorder tree traversal 2. Preorder tree traversal 3. Postorder tree traversal
  • 5. Inorder Tree Traversal The left subtree is visited first, followed by the root, and finally the right subtree in this traversal strategy. Always keep in mind that any node might be a subtree in and of itself. The output of a binary tree traversal in order produces sorted key values in ascending order. C Code Let's write a basic C program for Inorder traversal of the binary search tree. 1. //C Program for Inorder traversal of the binary search tree 2. 3. #include<stdio.h> 4. #include<stdlib.h> 5. 6. struct node 7. { 8. int key; 9. struct node *left; 10. struct node *right; 11. }; 12. 13. //return a new node with the given value 14. struct node *getNode(int val) 15. { 16. struct node *newNode; 17. 18. newNode = malloc(sizeof(struct node)); 19. 20. newNode->key = val; 21. newNode->left = NULL; 22. newNode->right = NULL; 23. 24. return newNode; 25. } 26. 27. //inserts nodes in the binary search tree 28. struct node *insertNode(struct node *root, int val)
  • 6. 29. { 30. if(root == NULL) 31. return getNode(val); 32. 33. if(root->key < val) 34. root->right = insertNode(root->right,val); 35. 36. if(root->key > val) 37. root->left = insertNode(root->left,val); 38. 39. return root; 40. } 41. 42. //inorder traversal of the binary search tree 43. void inorder(struct node *root) 44. { 45. if(root == NULL) 46. return; 47. 48. //traverse the left subtree 49. inorder(root->left); 50. 51. //visit the root 52. printf("%d ",root->key); 53. 54. //traverse the right subtree 55. inorder(root->right); 56. } 57. 58. int main() 59. { 60. struct node *root = NULL; 61. 62. 63. int data; 64. char ch;
  • 7. 65. /* Do while loop to display various options to select from to decide the i nput */ 66. do 67. { 68. printf("nSelect one of the operations::"); 69. printf("n1. To insert a new node in the Binary Tree"); 70. printf("n2. To display the nodes of the Binary Tree(via Inorder Traversal).n"); 71. 72. int choice; 73. scanf("%d",&choice); 74. switch (choice) 75. { 76. case 1 : 77. printf("nEnter the value to be insertedn"); 78. scanf("%d",&data); 79. root = insertNode(root,data); 80. break; 81. case 2 : 82. printf("nInorder Traversal of the Binary Tree::n"); 83. inorder(root); 84. break; 85. default : 86. printf("Wrong Entryn"); 87. break; 88. } 89. 90. printf("nDo you want to continue (Type y or n)n"); 91. scanf(" %c",&ch); 92. } while (ch == 'Y'|| ch == 'y'); 93. 94. return 0; 95. } Output The above C code hives the following output. Select one of the operations:: 1. To insert a new node in the Binary Tree
  • 8. 2. To display the nodes of the Binary Tree (via Inorder Traversal). 1 Enter the value to be inserted 12 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Inorder Traversal). 1 Enter the value to be inserted 98 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Inorder Traversal). 1 Enter the value to be inserted 23 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Inorder Traversal). 1 Enter the value to be inserted 78 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Inorder Traversal). 1 Enter the value to be inserted 45 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Inorder Traversal). 1 Enter the value to be inserted 87
  • 9. Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Inorder Traversal). 2 Inorder Traversal of the Binary Tree:: 12 23 45 78 87 98 Do you want to continue (Type y or n) n Preorder Tree Traversal In this traversal method, the root node is visited first, then the left subtree, and finally the right subtree. Code Let's write a C code for the Preorder traversal of the binary search tree. 1. /* 2. * Program: Preorder traversal of the binary search tree 3. * Language: C 4. */ 5. 6. #include<stdio.h> 7. #include<stdlib.h> 8. 9. struct node 10. { 11. int key; 12. struct node *left; 13. struct node *right; 14. }; 15. 16. //return a new node with the given value 17. struct node *getNode(int val) 18. { 19. struct node *newNode; 20. 21. newNode = malloc(sizeof(struct node)); 22.
  • 10. 23. newNode->key = val; 24. newNode->left = NULL; 25. newNode->right = NULL; 26. 27. return newNode; 28. } 29. 30. //inserts nodes in the binary search tree 31. struct node *insertNode(struct node *root, int val) 32. { 33. if(root == NULL) 34. return getNode(val); 35. 36. if(root->key < val) 37. root->right = insertNode(root->right,val); 38. 39. if(root->key > val) 40. root->left = insertNode(root->left,val); 41. 42. return root; 43. } 44. 45. //preorder traversal of the binary search tree 46. void preorder(struct node *root) 47. { 48. if(root == NULL) 49. return; 50. 51. //visit the root 52. printf("%d ",root->key); 53. 54. //traverse the left subtree 55. preorder(root->left); 56. 57. //traverse the right subtree 58. preorder(root->right); 59. }
  • 11. 60. 61. int main() 62. { 63. struct node *root = NULL; 64. 65. int data; 66. char ch; 67. /* Do while loop to display various options to select from to decide the i nput */ 68. do 69. { 70. printf("nSelect one of the operations::"); 71. printf("n1. To insert a new node in the Binary Tree"); 72. printf("n2. To display the nodes of the Binary Tree(via Preorder Traversal).n"); 73. 74. int choice; 75. scanf("%d",&choice); 76. switch (choice) 77. { 78. case 1 : 79. printf("nEnter the value to be insertedn"); 80. scanf("%d",&data); 81. root = insertNode(root,data); 82. break; 83. case 2 : 84. printf("nPreorder Traversal of the Binary Tree::n"); 85. preorder(root); 86. break; 87. default : 88. printf("Wrong Entryn"); 89. break; 90. } 91. 92. printf("nDo you want to continue (Type y or n)n"); 93. scanf(" %c",&ch); 94. } while (ch == 'Y'|| ch == 'y');
  • 12. 95. 96. return 0; 97. } Output: Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Preorder Traversal). 1 Enter the value to be inserted 45 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Preorder Traversal). 1 Enter the value to be inserted 53 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Preorder Traversal). 1 Enter the value to be inserted 1 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Preorder Traversal). 1 Enter the value to be inserted 2 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Preorder Traversal). 1 Enter the value to be inserted 97
  • 13. Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Preorder Traversal). 1 Enter the value to be inserted 22 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Preorder Traversal). 2 Preorder Traversal of the Binary Tree:: 45 1 2 22 53 97 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Preorder Traversal). 1 Enter the value to be inserted 76 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Preorder Traversal). 1 Enter the value to be inserted 30 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Preorder Traversal). 1 Enter the value to be inserted 67 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Preorder Traversal). 1
  • 14. Enter the value to be inserted 4 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Preorder Traversal). 2 Preorder Traversal of the Binary Tree:: 45 1 2 22 4 30 53 97 76 67 Do you want to continue (Type y or n) n Postorder Tree Traversal The root node is visited last in this traversal method, hence the name. First, we traverse the left subtree, then the right subtree, and finally the root node. Code Let's write a program for Postorder traversal of the binary search tree. 1. /* 2. * Program: Postorder traversal of the binary search tree 3. * Language: C 4. */ 5. 6. #include<stdio.h> 7. #include<stdlib.h> 8. 9. struct node 10. { 11. int key; 12. struct node *left; 13. struct node *right; 14. }; 15. 16. //return a new node with the given value 17. struct node *getNode(int val) 18. { 19. struct node *newNode;
  • 15. 20. 21. newNode = malloc(sizeof(struct node)); 22. 23. newNode->key = val; 24. newNode->left = NULL; 25. newNode->right = NULL; 26. 27. return newNode; 28. } 29. //inserts nodes in the binary search tree 30. struct node *insertNode(struct node *root, int val) 31. { 32. if(root == NULL) 33. return getNode(val); 34. 35. if(root->key < val) 36. root->right = insertNode(root->right,val); 37. 38. if(root->key > val) 39. root->left = insertNode(root->left,val); 40. 41. return root; 42. } 43. 44. //postorder traversal of the binary search tree 45. void postorder(struct node *root) 46. { 47. if(root == NULL) 48. return; 49. 50. //traverse the left subtree 51. postorder(root->left); 52. 53. //traverse the right subtree 54. postorder(root->right); 55. 56. //visit the root
  • 16. 57. printf("%d ",root->key); 58. } 59. int main() 60. { 61. struct node *root = NULL; 62. 63. 64. int data; 65. char ch; 66. /* Do while loop to display various options to select from to decide the input */ 67. do 68. { 69. printf("nSelect one of the operations::"); 70. printf("n1. To insert a new node in the Binary Tree"); 71. printf("n2. To display the nodes of the Binary Tree(via Postorder Trave rsal).n"); 72. 73. int choice; 74. scanf("%d",&choice); 75. switch (choice) 76. { 77. case 1 : 78. printf("nEnter the value to be insertedn"); 79. scanf("%d",&data); 80. root = insertNode(root,data); 81. break; 82. case 2 : 83. printf("nPostorder Traversal of the Binary Tree::n"); 84. postorder(root); 85. break; 86. default : 87. printf("Wrong Entryn"); 88. break; 89. } 90. 91. printf("nDo you want to continue (Type y or n)n");
  • 17. 92. scanf(" %c",&ch); 93. } while (ch == 'Y'|| ch == 'y'); 94. 95. return 0; 96. } Output: Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Postorder Traversal). 1 Enter the value to be inserted 12 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Postorder Traversal). 1 Enter the value to be inserted 31 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Postorder Traversal). 24 Wrong Entry Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Postorder Traversal). 1 Enter the value to be inserted 24 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Postorder Traversal). 1 Enter the value to be inserted 88
  • 18. Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Postorder Traversal). 1 Enter the value to be inserted 67 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Postorder Traversal). 1 Enter the value to be inserted 56 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Postorder Traversal). 1 Enter the value to be inserted 90 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Postorder Traversal). 1 Enter the value to be inserted 44 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Postorder Traversal). 1 Enter the value to be inserted 71 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree
  • 19. 2. To display the nodes of the Binary Tree(via Postorder Traversal). 1 Enter the value to be inserted 38 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Postorder Traversal). 1 Enter the value to be inserted 29 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Postorder Traversal). 2 Postorder Traversal of the Binary Tree:: 29 24 38 44 56 71 67 90 88 31 12 Do you want to continue (Type y or n) n We have seen the different C programs to implement inorder, preorder, and postorder traversal of the nodes of the Binary tree. Now let us write a code to perform all three types of traversal in a single program. Code 1. //Binary tree traversal: 2. 3. #include <stdio.h> 4. // #include <conio.h> 5. #include <malloc.h> 6. struct node 7. { 8. struct node *left; 9. int data; 10. struct node *right; 11. }; 12. 13. void main() 14. {
  • 20. 15. void insert(struct node **,int); 16. void inorder(struct node *); 17. void postorder(struct node *); 18. void preorder(struct node *); 19. 20. struct node *ptr = NULL; 21. int no,i,num; 22. 23. // ptr = NULL; 24. // ptr->data=0; 25. 26. int data; 27. char ch; 28. /* Do while loop to display various options to select from to decide the input */ 29. do 30. { 31. printf("nSelect one of the operations::"); 32. printf("n1. To insert a new node in the Binary Tree"); 33. printf("n2. To display the nodes of the Binary Tree(via Preorder Travers al)."); 34. printf("n3. To display the nodes of the Binary Tree(via Inorder Traversal)."); 35. printf("n4. To display the nodes of the Binary Tree(via Postorder Trave rsal).n"); 36. 37. int choice; 38. scanf("%d",&choice); 39. switch (choice) 40. { 41. case 1 : 42. printf("nEnter the value to be insertedn"); 43. scanf("%d",&data); 44. insert(&ptr,data); 45. break; 46. case 2 : 47. printf("nPreorder Traversal of the Binary Tree::n"); 48. preorder(ptr);
  • 21. 49. break; 50. case 3 : 51. printf("nInorder Traversal of the Binary Tree::n"); 52. inorder(ptr); 53. break; 54. case 4 : 55. printf("nPostorder Traversal of the Binary Tree::n"); 56. postorder(ptr); 57. break; 58. default : 59. printf("Wrong Entryn"); 60. break; 61. } 62. 63. printf("nDo you want to continue (Type y or n)n"); 64. scanf(" %c",&ch); 65. } while (ch == 'Y'|| ch == 'y'); 66. 67. 68. // printf("nProgram for Tree Traversaln"); 69. // printf("Enter the number of nodes to add to the tree.<BR>n"); 70. // scanf("%d",&no); 71. 72. // for(i=0;i<no;i++) 73. // { 74. // printf("Enter the itemn"); 75. // scanf("%d",&num); 76. // insert(&ptr,num); 77. // } 78. 79. // //getch(); 80. // printf("nINORDER TRAVERSALn"); 81. // inorder(ptr); 82. 83. // printf("nPREORDER TRAVERSALn"); 84. // preorder(ptr); 85.
  • 22. 86. // printf("nPOSTORDER TRAVERSALn"); 87. // postorder(ptr); 88. 89. } 90. 91. void insert(struct node **p,int num) 92. { 93. if((*p)==NULL) 94. { 95. printf("Leaf node created."); 96. (*p)=malloc(sizeof(struct node)); 97. (*p)->left = NULL; 98. (*p)->right = NULL; 99. (*p)->data = num; 100. return; 101. } 102. else 103. { 104. if(num==(*p)->data) 105. { 106. printf("nREPEATED ENTRY ERROR VALUE REJECTEDn"); 107. return; 108. } 109. if(num<(*p)->data) 110. { 111. printf("nDirected to left link.n"); 112. insert(&((*p)->left),num); 113. } 114. else 115. { 116. printf("Directed to right link.n"); 117. insert(&((*p)->right),num); 118. } 119. } 120. return; 121. } 122.
  • 23. 123. void inorder(struct node *p) 124. { 125. if(p!=NULL) 126. { 127. inorder(p->left); 128. printf("%d ",p->data); 129. inorder(p->right); 130. } 131. else 132. return; 133. } 134. 135. void preorder(struct node *p) 136. { 137. if(p!=NULL) 138. { 139. printf("%d ",p->data); 140. preorder(p->left); 141. preorder(p->right); 142. } 143. else 144. return; 145. } 146. 147. void postorder(struct node *p) 148. { 149. if(p!=NULL) 150. { 151. postorder(p->left); 152. postorder(p->right); 153. printf("%d ",p->data); 154. } 155. else 156. return; 157. } Output:
  • 24. Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Preorder Traversal). 3. To display the nodes of the Binary Tree(via Inorder Traversal). 4. To display the nodes of the Binary Tree(via Postorder Traversal). 1 Enter the value to be inserted 2 Leaf node created. Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Preorder Traversal). 3. To display the nodes of the Binary Tree(via Inorder Traversal). 4. To display the nodes of the Binary Tree(via Postorder Traversal). 1 Enter the value to be inserted 5 Directed to right link. Leaf node created. Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Preorder Traversal). 3. To display the nodes of the Binary Tree(via Inorder Traversal). 4. To display the nodes of the Binary Tree(via Postorder Traversal). 1 Enter the value to be inserted 7 Directed to right link. Directed to right link. Leaf node created. Do you want to continue (Type y or n) Y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Preorder Traversal). 3. To display the nodes of the Binary Tree(via Inorder Traversal). 4. To display the nodes of the Binary Tree(via Postorder Traversal). 1 Enter the value to be inserted 9 Directed to right link. Directed to right link. Directed to right link. Leaf node created. Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Preorder Traversal).
  • 25. 3. To display the nodes of the Binary Tree(via Inorder Traversal). 4. To display the nodes of the Binary Tree(via Postorder Traversal). 1 Enter the value to be inserted 31 Directed to right link. Directed to right link. Directed to right link. Directed to right link. Leaf node created. Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Preorder Traversal). 3. To display the nodes of the Binary Tree(via Inorder Traversal). 4. To display the nodes of the Binary Tree(via Postorder Traversal). 1 Enter the value to be inserted 78 Directed to right link. Directed to right link. Directed to right link. Directed to right link. Directed to right link. Leaf node created. Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Preorder Traversal). 3. To display the nodes of the Binary Tree(via Inorder Traversal). 4. To display the nodes of the Binary Tree(via Postorder Traversal). 2 Preorder Traversal of the Binary Tree:: 2 5 7 9 31 78 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Preorder Traversal). 3. To display the nodes of the Binary Tree(via Inorder Traversal). 4. To display the nodes of the Binary Tree(via Postorder Traversal). 3 Inorder Traversal of the Binary Tree:: 2 5 7 9 31 78 Do you want to continue (Type y or n) y Select one of the operations:: 1. To insert a new node in the Binary Tree 2. To display the nodes of the Binary Tree(via Preorder Traversal). 3. To display the nodes of the Binary Tree(via Inorder Traversal). 4. To display the nodes of the Binary Tree(via Postorder Traversal).
  • 26. 4 Postorder Traversal of the Binary Tree:: 78 31 9 7 5 2 Do you want to continue (Type y or n) n Threaded Binary Tree In this article, we will understand about the threaded binary tree in detail. What do you mean by Threaded Binary Tree? In the linked representation of binary trees, more than one half of the link fields contain NULL values which results in wastage of storage space. If a binary tree consists of n nodes then n+1 link fields contain NULL values. So in order to effectively manage the space, a method was devised by Perlis and Thornton in which the NULL links are replaced with special links known as threads. Such binary trees with threads are known as threaded binary trees. Each node in a threaded binary tree either contains a link to its child node or thread to other nodes in the tree. Types of Threaded Binary Tree There are two types of threaded Binary Tree: o One-way threaded Binary Tree
  • 27. o Two-way threaded Binary Tree One-way threaded Binary trees: In one-way threaded binary trees, a thread will appear either in the right or left link field of a node. If it appears in the right link field of a node then it will point to the next node that will appear on performing in order traversal. Such trees are called Right threaded binary trees. If thread appears in the left field of a node then it will point to the nodes inorder predecessor. Such trees are called Left threaded binary trees. Left threaded binary trees are used less often as they don't yield the last advantages of right threaded binary trees. In one-way threaded binary trees, the right link field of last node and left link field of first node contains a NULL. In order to distinguish threads from normal links they are represented by dotted lines. The above figure shows the inorder traversal of this binary tree yields D, B, E, A, C, F. When this tree is represented as a right threaded binary tree, the right link field of leaf node D which contains a NULL value is replaced with a thread that points to node B
  • 28. which is the inorder successor of a node D. In the same way other nodes containing values in the right link field will contain NULL value. Two-way threaded Binary Trees: In two-way threaded Binary trees, the right link field of a node containing NULL values is replaced by a thread that points to nodes inorder successor and left field of a node containing NULL values is replaced by a thread that points to nodes inorder predecessor. ADVERTISEMENT The above figure shows the inorder traversal of this binary tree yields D, B, E, G, A, C, F. If we consider the two-way threaded Binary tree, the node E whose left field contains NULL is replaced by a thread pointing to its inorder predecessor i.e. node B. Similarly, for node G whose right and left linked fields contain NULL values are replaced by threads such that right link field points to its inorder successor and left link field points
  • 29. to its inorder predecessor. In the same way, other nodes containing NULL values in their link fields are filled with threads. ADVERTISEMENT In the above figure of two-way threaded Binary tree, we noticed that no left thread is possible for the first node and no right thread is possible for the last node. This is because they don't have any inorder predecessor and successor respectively. This is indicated by threads pointing nowhere. So in order to maintain the uniformity of threads, we maintain a special node called the header node. The header node does not contain any data part and its left link field points to the root node and its right link field points to itself. If this header node is included in the two-way threaded Binary tree then this node becomes the inorder predecessor of the first node and inorder successor of the last node. Now threads of left link fields of the first node and right link fields of the last node will point to the header node. Algorithm for Inorder Traversal of Threaded Binary Tree: 1. ALgorithm Inorder(I) 2. { 3. ThreadedTreeNode *Header; 4. Header=I; 5. while(1) 6. { 7. I=fnFindInorder_Successor(H);
  • 30. 8. if(I==Header) 9. return; 10. else 11. print(I->info); 12. } 13. } 14. In the above algorithm, we have discussed the Inorder traversal of Threaded bi nary trees. 15. Pseudocode of Threaded Tree in C: 16. #include <stdio.h> 17. #include <stdlib.h> 18. typedef enum {false,true} boolean; 19. struct node *in_succ(struct node *p); 20. struct node *in_pred(struct node *p); 21. struct node *insert(struct node *root, int ikey); 22. struct node *del(struct node *root, int dkey); 23. struct node *case_a(struct node *root, struct node *par,struct node *ptr); 24. struct node *case_b(struct node *root,struct node *par,struct node *ptr); 25. struct node *case_c(struct node *root, struct node *par,struct node *ptr); 26. void inorder( struct node *root); 27. void preorder( struct node *root); 28. 29. struct node 30. { 31. struct node *left; 32. boolean lthread; 33. int info; 34. boolean rthread; 35. struct node *right; 36. }; 37. int main( ) 38. { 39. clrscr(); 40. int choice,num; 41. struct node *root=NULL; 42. while(1) 43. {
  • 31. 44. printf("Program of Threaded Tree in Cn"); 45. printf("1.Insertn"); 46. printf("2.Deleten"); 47. printf("3.Inorder Traversaln"); 48. printf("4.Preorder Traversaln"); 49. printf("5.Quitn"); 50. printf("nEnter your choice : "); 51. scanf("%d",&choice); 52. switch(choice) 53. { 54. case 1: 55. printf("nEnter the number to be inserted : "); 56. scanf("%d",&num); 57. root = insert(root,num); 58. break; 59. case 2: 60. printf("nEnter the number to be deleted : "); 61. scanf("%d",&num); 62. root = del(root,num); 63. break; 64. case 3: 65. inorder(root); 66. break; 67. case 4: 68. preorder(root); 69. break; 70. case 5: 71. exit(1); 72. 73. default: 74. printf("nWrong choicen"); 75. } 76. } 77. return 0; 78. } 79. struct node *insert(struct node *root, int ikey) 80. {
  • 32. 81. struct node *tmp,*par,*ptr; 82. int found=0; 83. ptr = root; 84. par = NULL; 85. while( ptr!=NULL ) 86. { 87. if( ikey == ptr->info) 88. { 89. found =1; 90. break; 91. } 92. par = ptr; 93. if(ikey < ptr->info) 94. { 95. if(ptr->lthread == false) 96. ptr = ptr->left; 97. else 98. break; 99. } 100. else 101. { 102. if(ptr->rthread == false) 103. ptr = ptr->right; 104. else 105. break; 106. } 107. } 108. if(found) 109. printf("nDuplicate key"); 110. else 111. { 112. tmp=(struct node *)malloc(sizeof(struct node)); 113. tmp->info=ikey; 114. tmp->lthread = true; 115. tmp->rthread = true; 116. if(par==NULL) 117. {
  • 33. 118. root=tmp; 119. tmp->left=NULL; 120. tmp->right=NULL; 121. } 122. else if( ikey < par->info ) 123. { 124. tmp->left=par->left; 125. tmp->right=par; 126. par->lthread=false; 127. par->left=tmp; 128. } 129. else 130. { 131. tmp->left=par; 132. tmp->right=par->right; 133. par->rthread=false; 134. par->right=tmp; 135. } 136. } 137. return root; 138. } 139. 140. struct node *del(struct node *root, int dkey) 141. { 142. struct node *par,*ptr; 143. int found=0; 144. ptr = root; 145. par = NULL; 146. while( ptr!=NULL) 147. { 148. if( dkey == ptr->info) 149. { 150. found =1; 151. break; 152. } 153. par = ptr; 154. if(dkey < ptr->info)
  • 34. 155. { 156. if(ptr->lthread == false) 157. ptr = ptr->left; 158. else 159. break; 160. } 161. else 162. { 163. if(ptr->rthread == false) 164. ptr = ptr->right; 165. else 166. break; 167. } 168. } 169. if(found==0) 170. printf("ndkey not present in tree"); 171. else if(ptr->lthread==false && ptr->rthread==false)/*2 children*/ 172. root = case_c(root,par,ptr); 173. else if(ptr->lthread==false ) 174. root = case_b(root, par,ptr); 175. else if(ptr->rthread==false) 176. root = case_b(root, par,ptr); 177. else 178. root = case_a(root,par,ptr); 179. return root; 180. } 181. 182. struct node *case_a(struct node *root, struct node *par,struct node *ptr ) 183. { 184. if(par==NULL) 185. root=NULL; 186. else if(ptr==par->left) 187. { 188. par->lthread=true; 189. par->left=ptr->left; 190. }
  • 35. 191. else 192. { 193. par->rthread=true; 194. par->right=ptr->right; 195. } 196. free(ptr); 197. return root; 198. } 199. struct node *case_b(struct node *root,struct node *par,struct node *ptr) 200. { 201. struct node *child,*s,*p; 202. if(ptr->lthread==false) 203. child=ptr->left; 204. else 205. child=ptr->right; 206. if(par==NULL ) 207. root=child; 208. else if( ptr==par->left) 209. par->left=child; 210. else 211. par->right=child; 212. s=in_succ(ptr); 213. p=in_pred(ptr); 214. if(ptr->lthread==false) 215. p->right=s; 216. else 217. { 218. if(ptr->rthread==false) 219. s->left=p; 220. } 221. free(ptr); 222. return root; 223. } 224. struct node *case_c(struct node *root, struct node *par,struct node *ptr) 225. {
  • 36. 226. struct node *succ,*parsucc; 227. parsucc = ptr; 228. succ = ptr->right; 229. while(succ->left!=NULL) 230. { 231. parsucc = succ; 232. succ = succ->left; 233. } 234. ptr->info = succ->info; 235. if(succ->lthread==true && succ->rthread==true) 236. root = case_a(root, parsucc,succ); 237. else 238. root = case_b(root, parsucc,succ); 239. return root; 240. } 241. struct node *in_succ(struct node *ptr) 242. { 243. if(ptr->rthread==true) 244. return ptr->right; 245. else 246. { 247. ptr=ptr->right; 248. while(ptr->lthread==false) 249. ptr=ptr->left; 250. return ptr; 251. } 252. } 253. struct node *in_pred(struct node *ptr) 254. { 255. if(ptr->lthread==true) 256. return ptr->left; 257. else 258. { 259. ptr=ptr->left; 260. while(ptr->rthread==false) 261. ptr=ptr->right; 262. return ptr;
  • 37. 263. } 264. } 265. void inorder( struct node *root) 266. { 267. struct node *ptr; 268. if(root == NULL ) 269. { 270. printf("Tree is empty"); 271. return; 272. } 273. ptr=root; 274. while(ptr->lthread==false) 275. ptr=ptr->left; 276. while( ptr!=NULL ) 277. { 278. printf("%d ",ptr->info); 279. ptr=in_succ(ptr); 280. } 281. } 282. void preorder(struct node *root ) 283. { 284. struct node *ptr; 285. if(root==NULL) 286. { 287. printf("Tree is empty"); 288. return; 289. } 290. ptr=root; 291. while(ptr!=NULL) 292. { 293. printf("%d ",ptr->info); 294. if(ptr->lthread==false) 295. ptr=ptr->left; 296. else if(ptr->rthread==false) 297. ptr=ptr->right; 298. else 299. {
  • 38. 300. while(ptr!=NULL && ptr->rthread==true) 301. ptr=ptr->right; 302. if(ptr!=NULL) 303. ptr=ptr->right; 304. } 305. } 306. } Explanation: In the above example, we have created a threaded binary tree for various operations. Output:
  • 40. Advantages of Threaded Binary Tree: o In threaded binary tree, linear and fast traversal of nodes in the tree so there is no requirement of stack. If the stack is used then it consumes a lot of memory and time. o It is more general as one can efficiently determine the successor and predecessor of any node by simply following the thread and links. It almost behaves like a circular linked list. Disadvantages of Threaded Binary Tree: o When implemented, the threaded binary tree needs to maintain the extra information for each node to indicate whether the link field of each node points to an ordinary node or the node's successor and predecessor. o Insertion into and deletion from a threaded binary tree are more time consuming since both threads and ordinary links need to be maintained.