I am trying to build a simple tree program and traverse it in inorder,preorder and postorder formats. The code I am using is this :
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node* lchild;
struct node* rchild;
};
typedef struct node* NODE;
NODE getNode()
{
NODE temp;
temp = (NODE)malloc(sizeof(struct node));
return temp;
}
NODE insert(NODE root,int item)
{
NODE temp,prev,cur;
temp = getNode();
temp->info = item;
temp->lchild = NULL;
temp->rchild = NULL;
if(root==NULL)
{return temp;}
prev = NULL;
cur = root;
while(cur!=NULL)
{
prev = cur;
if(item<cur->info)
{
cur = cur->lchild;
}
else if(item>cur->info)
{
cur = cur->rchild;
}
}
if(item<prev->info)
{
prev->lchild = temp;
}
else if(item>prev->info)
{
prev->rchild = temp;
}
return root;
}
void inorderTraversal(NODE root)
{
if(root!=NULL)
{
inorderTraversal(root->lchild);
printf("%d\t",root->info);
inorderTraversal(root->rchild);
}
else
{
return;
}
}
void preorderTraversal(NODE root)
{
if(root!=NULL)
{
printf("%d\t",root->info);
preorderTraversal(root->lchild);
preorderTraversal(root->rchild);
}
else
{
return;
}
}
void postorderTraversal(NODE root)
{
if(root!=NULL)
{
postorderTraversal(root->lchild);
postorderTraversal(root->rchild);
printf("%d\t",root->info);
}
else
{
return;
}
}
int main() {
NODE root;
root = getNode();
root = NULL;
root = insert(root,10);
root = insert(root,20);
root = insert(root,15);
printf("Root is: %d\n",root->info);
printf("Inorder Traversal is :");
inorderTraversal(root);
printf("\n");
printf("Preorder traversal is :");
preorderTraversal(root);
printf("\n");
printf("Postorder traversal is :");
postorderTraversal(root);
printf("\n");
return 0;
}
and the output I get is this :
Root is: 10 Inorder Traversal is :10 15 20
Preorder traversal is :10 20 15
Postorder traversal is :15 20 10
ie 10 is assigned as root, when it should ideally be 15 with 10 on the left and 15 on the right. What is the error here and how do I fix this ?
Thanks !
The tree structure you are ending up is something like below
10
\
20
/
15
The order of traversal will be as below: In-order: 10 15 20 Pre-order: 10 20 15 Post-order: 15 20 10
BST does maintain the property that elements in the lef-subtree are smaller than the elements in the right sub-tree. But, they don't do self-balancing like AVL or Red-black tree.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.