Saturday, 26 January 2013

Trees

Problem:

Write a code to pack and unpack a binary tree.

Sol: Each node will be encapsulated in '[' and ']'.
Empty tree: []
Tree with single node: [4[][]]
Tree: 4--8  ==> [4[7[][]][8[][]]]
         |
         7
Working code



 #include <iostream>  
 #include <stdio.h>  
 #include <cstdlib>  
 #include <cstring>  
 #include <stack>  
 #include <list>  
 using namespace std;  
 struct node {  
  int data;  
  struct node* left;  
  struct node* right;  
 };  
 void print(struct node* root) {  
  cout<<"[";  
  if(root != NULL) {  
  cout<<root->data;  
  print(root->left);  
  print(root->right);  
  }  
  cout<<"]";  
  return;  
 }  
 //use stack.  
 //node: [val<left><right>]  
 stack<struct node*> tree;  
 struct node* unpack(char* str) {  
  int i=0;  
  while(str[i] != '\0') {  
  if(str[i] == '[') {  
   tree.push(NULL);  
   i++;  
  } else if (str[i] == ']') {  
   if(str[i-1] == ']') {  
   struct node* right = tree.top();tree.pop();  
   struct node* left = tree.top();tree.pop();  
   struct node* parent = tree.top();tree.pop();  
   if(parent != NULL) {  
    parent->left = left;  
    parent->right = right;  
   }  
   if(tree.size() > 1) {  
    tree.pop();  
    tree.push(parent);  
   } else  
    return parent;  
   } else if(str[i-1] == '[') {  
   if(tree.size() == 1)return NULL;  
   }  
   i++;  
  } else {  
   int j;  
   for(j=i;str[j] != '[' && str[j] != ']';j++);  
   int sum =0;int mult = 1;  
   for(int k=j-1;k >=i;k--) {  
   sum += mult * (str[k]-48);  
   mult *= 10;  
   }  
   struct node* node = (struct node*)malloc(sizeof(struct node));  
   node->left = NULL;  
   node->right = NULL;  
   node->data = sum;  
   tree.push(node);  
   i=j;  
  }  
  }  
 }  
 int main() {  
  char* str = new char[100];  
  cin>>str;  
  struct node* root = unpack(str);  
  print(root);  
  cout<<endl;  
  return 0;  
 }  

No comments:

Post a Comment