Advertisement
sak1b

https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/

Dec 10th, 2020
631
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.04 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10.  * };
  11.  */
  12. class Solution {
  13. public:
  14.  
  15.    
  16.     TreeNode* go_deep(vector<pair<int,int>>& arr,int ind, int depth)
  17.     {
  18.         if(ind>=arr.size()) return NULL;
  19.         if(arr[ind].second==depth)
  20.         {
  21.             TreeNode *temp= new TreeNode(arr[ind].first);
  22.  
  23.             temp->left= go_deep(arr, ind+1, depth+1);
  24.             temp->right = go_deep(arr, ind+1, depth+1);
  25.             return temp;
  26.         }
  27.         return NULL;
  28.     }
  29.  
  30.    
  31.     TreeNode* recoverFromPreorder(string S) {
  32.        
  33.         int n=S.length();
  34.         int depth=0;
  35.         string ss="";
  36.         int i;
  37.         int j;
  38.         int x=0;
  39.         map<int,int> height;
  40.  
  41.         pair<int, int> PAIR1;
  42.         vector<pair<int,int>> container;
  43.  
  44.  
  45.  
  46.         for(i=0;i<n;i++)
  47.         {
  48.             if(S[i]!='-')
  49.             {   ss="";
  50.                 for(j=i;j<n;j++)
  51.                 {
  52.                     if(S[j]!='-')
  53.                     {
  54.                        ss+=S[j];
  55.                     }
  56.                     else{
  57.                         i=j-1;
  58.                         break;
  59.                     }
  60.                 }
  61.                 i=j-1;
  62.                // cout<<ss<<"-> "<<depth<<endl;
  63.                 stringstream conv(ss);
  64.                 x=0;
  65.                 conv >> x;
  66.                 PAIR1.first=x;
  67.                 PAIR1.second=depth;
  68.                 container.push_back(PAIR1);
  69.                 ss="";
  70.                 depth=0;
  71.             }
  72.             else{
  73.                 depth++;
  74.             }
  75.         }
  76.  
  77.  
  78.         for(auto x:container)
  79.         {
  80.             cout<<x.first<<", "<<x.second<<endl;
  81.            
  82.         }
  83.  
  84.         return go_deep(container,0,0);
  85.        
  86.     }
  87. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement