Page 226 - DCAP407_DATA_STRUCTURE
P. 226
Unit 12: Binary Tree Traversals and Operations
}
}
return(bintree);
}
void inorder(struct tree*bintree) //Defining inorder function
{
if(bintree!=NULL) //Checks if tree is empty
{
inorder(bintree->left); //Calls the inorder function for left sub-trees
printf("%4ld",bintree->info); // Prints data of the node
inorder(bintree->right); // Inorder function of right sub-trees
}
}
Output:
Enter integers and 0 to quit
6 1 2 3 7 8 9 0
Inorder traversing of bintree
1 2 3 6 7 8 9
In this program,
1. First the structure tree is defined. It contains a variable info of long type and pointers to the right
and left sub-trees.
2. The variable bintree is declared as data type tree and initialized to NULL.
3. The function insert and inorder are globally declared.
4. In the main() function,
(a) First, the numbers to be entered are declared using long data type
(b) Then, the digit entered is read by the computer.
(c) If the digit is not 0, the insert() function is called to insert the entered digit into the binary
tree. Step b, and c are repeated until the digit entered is 0.
(d) Finally, the inorder() function is called to traverse the tree.
5. The insert() function is defined. It accepts a pointer to a tree and a digit to be inserted in the tree as
parameters. The insert function performs the following steps:
(a) It checks if the tree is empty or non-empty.
(b) If the tree is empty it assigns memory to the node, sets the left and right pointers of the node
as NULL and assigns the digit to the info variable of the node.
(c) If the tree is non-empty, then it performs the following steps:
(i) If the digit entered is less than the info stored in the node, it recursively calls itself to
enter the digit in the left sub-tree.
(ii) If the digit entered is greater than the info stored in the node, it recursively calls itself
to enter the digit in the left sub-tree.
LOVELY PROFESSIONAL UNIVERSITY 219