Skip to content

Commit

Permalink
Create 1028. Recover a Tree From Preorder Traversal (#723)
Browse files Browse the repository at this point in the history
  • Loading branch information
Chayandas07 authored Feb 22, 2025
2 parents ef4354d + d76a156 commit ee800b8
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions 1028. Recover a Tree From Preorder Traversal
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* solve(string s, int& i, int depth) {
int n = s.size();
if (i >= n)
return NULL;

int j = i;
while (j < n && s[j] == '-') {
j++;
}
int dash = j - i;

if (dash != depth)
return NULL;

i += dash;
int num = 0;
while (i < n && isdigit(s[i])) {
num = num * 10 + (s[i] - '0');
i++;
}

TreeNode* root = new TreeNode(num);
root->left = solve(s, i, depth + 1);
root->right = solve(s, i, depth + 1);
return root;
}

TreeNode* recoverFromPreorder(string traversal) {
int i = 0;
return solve(traversal, i, 0);
}
};

0 comments on commit ee800b8

Please sign in to comment.