Recursion to iterative inorder tree traversal

Viewed 9
// C++ program for different tree traversals
#include <bits/stdc++.h>
using namespace std;

/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct Node {
    int data;
    struct Node *left, *right;
};

// Utility function to create a new tree node
Node* newNode(int data)
{
    Node* temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}

/* Given a binary tree, print its nodes in inorder*/
void printInorder(struct Node* node)
{
    if (node == NULL)
        return;

    /* first recur on left child */
    printInorder(node->left);

    /* then print the data of node */
    cout << node->data << " ";

    /* now recur on right child */
    printInorder(node->right);
}

/* Driver code*/
int main()
{
    struct Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);


    // Function call
    cout << "\nInorder traversal of binary tree is \n";
    printInorder(root);


    return 0;
}

above is the recursion version of inorder traversal please help me to understand how to convert recursion code into iterative code using the above code I am interested in knowing how to convert recursive code to iterative version thank you

0 Answers
Related