Wednesday, August 1, 2012

Create a singly linked list from the Leaf nodes from a binary tree. Tree may be balanced or not. Linked List should be created in place (tree nodes should be used)

Code: O(n) time, O(log n) space complexity.

#include<iostream>
#include<stack>
using namespace std;
 
class Node
{
public:
        int data;
        Node *left,*right;
        Node(int d,Node *l=NULL,Node *r=NULL):data(d),left(l),right(r){}
};
void insert_after(Node *h,Node *temp)
{
    temp->right = h->right;
    h->right = temp;
}
Node *make_links(Node *head)
{
    if(head == NULL)
        return NULL;
 
    stack<Node *> st;
    Node *list = new Node(-1);
    Node *temp = head;
    Node *temp_list=list;
    while(true)
    {
        for(;temp;temp=temp->left)
            st.push(temp);
        if(st.empty())
            break;
        else{
            temp = st.top();
            st.pop();
            Node *l = temp->right;
            if(temp->left==NULL && temp->right==NULL)
            {
                insert_after(temp_list,temp);
                temp_list=temp_list->right;
            }
            temp = l;
        }
    }
    Node *l = list;
    list = list->right;
    delete l;
    return list;
}
void preorder_print(Node *head)
{
    if(head == NULL)
        return;
    cout<<head->data<<" ";
    preorder_print(head->left);
    preorder_print(head->right);
}
void inorder_print(Node *head)
{
    if(head == NULL)
        return;
    inorder_print(head->left);
    cout<<head->data<<" ";
    inorder_print(head->right);
}
int main()
{
        Node *head = new Node(10,new Node(5,new Node(2),new Node(7)),new Node(13,new Node(11),new Node(14)));
        preorder_print(head);cout<<endl;
        inorder_print(head);
        Node *ll = make_links(head);
        cout<<endl;
        for(;ll;ll=ll->right)
        cout<<(ll->data)<<" ";
}

No comments:

Post a Comment