Answers for "inorder traversal without recursion and stack"

C++
0

inorder traversal without recursion and stack

//Pragram in C++ to do inorder traversal of binary tree without recursion and stack
//using morris inorder traversal
btree* find_predecessesor(btree *root){
    btree *head = root;
    root = root->left;
  
    //go to rightmost node of left subtree
    while(root->right && root->right != head){
        root = root->right;
    }
    
    return root;
}

void morris_inorder(btree *root){
    while(root){
        if(!root->left){
          //when left subtree is empty
            cout<<root->data<<" ";
            root = root->right;
        } else{
            btree *link = find_predecessesor(root);
            if(link->right){
              //if left subtree has already been traversed
                link->right = NULL;
                cout<<root->data<<" ";
                root=root->right;
            } 
            else{
              //link predecessor node to current node 
                link->right = root;
                root=root->left;
            } 
        }
    }
}
Posted by: Guest on October-07-2021
0

inorder traversal without recursion

//Iterative Inorder binary tree traversal
void it_inOrder(btree *root)
{
    stack<btree*> s;
    while(root || !s.empty())
    {
         while(root)
         {
             s.push(root);
             root=root->left;
         }
         btree *p=s.top();
         s.pop();
         cout<<p->data<<" ";
         
         root=p->right;
    }
}
Posted by: Guest on October-05-2021

Code answers related to "inorder traversal without recursion and stack"

Browse Popular Code Answers by Language