Advertisement
nikunjsoni

1028

Apr 23rd, 2021
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 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.     TreeNode* recoverFromPreorder(string S) {
  15.         vector<TreeNode*> stk;
  16.         for(int i=0, val, level; i<S.length();){
  17.             // Get the level.
  18.             for(level=0; S[i]=='-'; i++)
  19.                 level++;
  20.            
  21.             // Get the value.
  22.             for(val=0; S[i]!='-' && i<S.length(); i++)
  23.                 val = val*10 + S[i]-'0';
  24.            
  25.             //Get the appropriate level in stack.
  26.             while(stk.size() > level) stk.pop_back();
  27.            
  28.             // Create the node.
  29.             TreeNode *node = new TreeNode(val);
  30.            
  31.             // If stack is not empty, insert at left or right appropriately.
  32.             if(!stk.empty()){
  33.                 TreeNode *last = stk.back();
  34.                 if(!last->left) last->left = node;
  35.                 else if(!last->right) last->right = node;
  36.             }
  37.             stk.push_back(node);
  38.         }
  39.         return stk.front();
  40.     }
  41. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement