Flatten BST to sorted list

 // Flatten BST to Sortlisted

#include<bits/stdc++.h>
using namespace std;
struct Node{
    int data;
    struct Node* left;
    struct Node* right;
    Node(int val){
        data=val;
        left=NULL;
        right=NULL;
    }
};

void fun(Node* parent){
    Node* curr = parent;
    while (curr != NULL)
        cout << curr->data << " ", curr = curr->right;
}

void inorder(Node* curr, Node* & prev){
    if(!curr) return;
    inorder(curr->left, prev);
    prev->left=NULL;
    prev->right=curr;
    prev=curr;
    inorder(curr->right, prev);

}

Node* flatten(Node* root){
    Node* dummy=new Node(-1);
    Node* prev=dummy;
    inorder(root, prev);
    prev->left=NULL;
    prev->right=NULL;
    Node* ret=dummy->right;
    return ret;

}

int main(){
       #ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
      struct Node* root=new Node(5);
      root->left=new Node(3);
      root->left->left=new Node(2);
      root->left->right=new Node(4);
      root->right=new Node(7);
      root->right->left=new Node(6);
      root->right->right=new Node(8);
      fun(flatten(root));




    return 0;
}

Comments

Popular posts from this blog

priority_queue

Alignment in css

Queue data structure in c++