Tuesday, 30 June 2015

Threaded Binary Tree



Threaded binary tree saves stack recursion space used for traversing a tree , by making traversal iterative istead of recursive.
    The right most null node is made to be ponted to its inorder successor while tree formation .
    So space complexity becomes O(1) from O(N)



#include<cstdio.h>
#include<iostream>


//structure of a node in a threded binary tree
struct treeNode{
    int data;
    struct treeNode* right;
    struct treeNode* left;
    bool isRightHanded;
       
};

struct treeNode* leftMost(struct  treeNode* curr)
{
    if (curr == NULL)
        return NULL;
    while (curr->left != NULL)
        curr = curr->left;
    return curr;

}



void traverseThrededTree(struct treeNode* root)
{
    if (root == NULL)
    {
        printf("Empty tree");
        return ;
    }

    struct treeNode* cur = leftMost(root);

    while (cur != NULL)
    {
        printf("%d", cur->data);

        //if node is right handed , go to next node
        if (cur->isRightHanded)
        {
            cur = cur->right;
        }
        else // else go to next leftmost node of the right node , if it exist
        {
            cur = leftMost(cur->right);
        }
    }




}

No comments:

Post a Comment