Quantcast
Viewing all articles
Browse latest Browse all 34

Binary tree inorder traversal without recursion using stack

In this blog we are going to discuss how to implement binary tree inorder traversal without recursion using stack.

Image may be NSFW.
Clik here to view.

#include <iostream>
#include<stack>
using namespace std;

typedef struct l
{
        struct l* left;
        struct l* right;
        int data;
} Tree;

Tree *node(int data)
{
    Tree *tmp = new Tree();
    tmp->left = NULL;
    tmp->right = NULL;
    tmp->data = data;
    return tmp;
}
void inorder(Tree* root)
{

}
void inorderTraversal(Tree* root)
{
    if (root == NULL) return ;

    Tree* current = root;
    stack<Tree*> s;
    int flag = 0;

    while (!flag)
    {
        while (current != NULL) // Inserting all leftmost nodes
        {
            s.push(current);
            current = current->left;
        }

        if (!s.empty())
        {
            current = s.top();
            cout << current->data<<" ";
            s.pop();
            current = current->right;
        }
        else
            flag = 1;
    }
}

int main()
{
    Tree* root = node(6);
    root->left = node(8);
    root->right = node(5);
    root->right->left = node(8);
    root->right->right = node(3);
    inorderTraversal(root);
    return 0;
}

 

The post Binary tree inorder traversal without recursion using stack appeared first on wikistack.


Viewing all articles
Browse latest Browse all 34

Trending Articles