Interview Questions For All

Interview Questions For All Who Are Waiting For Jobs

Thursday, July 24, 2008

Traversals of a Binary Tree

Write C code to implement the preorder(), inorder() and postorder() traversals. Whats their time complexities?


#include
struct binarysearchtree{
int data;
struct binarysearchtree* left;
struct binarysearchtree* right;
};
typedef struct binarysearchtree* tree;

void inorder_print(tree T)
{
if (T!=NULL)
{
printf("%d\n",T->data);
inorder_print(T->left);
inorder_print(T->right);
}
}

void postorder_print(tree T)
{
if (T==NULL)
{
return;
}
postorder_print(T->left);
postorder_print(T->right);
printf("%d\n",T->data);
}

void preorder_print(tree T)
{
if (T==NULL)
{
return;
}
printf("%d\n",T->data);
preorder_print(T->left);
preorder_print(T->right);

}


Each of them traverse all the nodes.
So the complexity is O(N).
piot at 8:03 AM

No comments:

Post a Comment

‹
›
Home
View web version
Powered by Blogger.