stillnotred

Untitled

Feb 22nd, 2025
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.29 KB | None | 0 0
  1. // struct TreeNode {
  2. //     int val;
  3. //     TreeNode *left;
  4. //     TreeNode *right;
  5. //     TreeNode() : val(0), left(nullptr), right(nullptr) {}
  6. //     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  7. //     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  8. // };
  9.  
  10. class Solution {
  11. public:
  12.     TreeNode* recoverFromPreorder(string a) {
  13.         vector<TreeNode*> st;
  14.         int i = 0, n = a.length();
  15.  
  16.         while (i < n){
  17.             int d = 0;
  18.             while(i < n && a[i] == '-'){
  19.                 i += 1;
  20.                 d += 1;
  21.             }
  22.             string cur = "";
  23.             while (i < n && isdigit(a[i])){
  24.                 cur += a[i];
  25.                 i++;
  26.             }
  27.             TreeNode* val = new TreeNode(std::stoi(cur));
  28.  
  29.             while(st.size() > d){
  30.                 st.pop_back();
  31.             }
  32.  
  33.             if(!st.empty()){
  34.                 if(st.back()->left == NULL){
  35.                     st.back()->left = val;
  36.                 }
  37.                 else{
  38.                     // assert(st.back()->right == NULL);
  39.                     st.back()->right = val;
  40.                 }
  41.             }
  42.             st.push_back(val);
  43.         }
  44.         // assert(st.size());
  45.         return st.front();
  46.     }
  47. };
  48.  
Advertisement
Add Comment
Please, Sign In to add comment