Sunday, September 9, 2012

Inorder Traversal of binary tree

Inorder traversal of binary tree - Recursive


  
typedef struct _binaryTreeNode
{
  struct _binaryTreeNode *left;
  struct _binaryTreeNode *right;
  void* object;
} TreeNode;

void inOrderTraversalRecursive(TreeNode* root) {  
   if (root == NULL )  
     return;  
   inOrderTraversalRecursive(root->left);  
   printf("%d ", *(int *) root->object);  
   inOrderTraversalRecursive(root->right);  
 }  

Inorder traversal of binary tree - Iterative

 void inOrderTraversalIterative(TreeNode* root) {  
   if (root == NULL )  
     return;     
   Stack *tempStack = createStack();   
   do {  
     while (root != NULL ) {  
       push(tempStack, root);  
       root = root->left;  
     }  
   
     if (isEmpty(tempStack) != 0) {  
       root = pop(tempStack);  
       printf("%d ", *((int*) root->object));  
       root = root->right;  
     }  
   } while ((isEmpty(tempStack) != 0) || root != NULL );  
 }  
PS: Stack related functions are here.

No comments:

Post a Comment