Skip to content

Commit 58c7017

Browse files
authored
Add files via upload
1 parent 32efd65 commit 58c7017

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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 traversal) {
15+
stack<TreeNode*> st;
16+
int i = 0, n = traversal.size();
17+
18+
while (i < n) {
19+
int depth = 0;
20+
// Count the number of dashes to determine depth
21+
while (i < n && traversal[i] == '-') {
22+
depth++;
23+
i++;
24+
}
25+
26+
// Extract the node value
27+
int value = 0;
28+
while (i < n && isdigit(traversal[i])) {
29+
value = value * 10 + (traversal[i] - '0');
30+
i++;
31+
}
32+
33+
// Create a new node
34+
TreeNode* node = new TreeNode(value);
35+
36+
// If the stack size is greater than depth, pop elements to find the correct parent
37+
while (st.size() > depth) {
38+
st.pop();
39+
}
40+
41+
// Attach the node to its parent
42+
if (!st.empty()) {
43+
if (!st.top()->left) {
44+
st.top()->left = node;
45+
} else {
46+
st.top()->right = node;
47+
}
48+
}
49+
50+
// Push the node to the stack
51+
st.push(node);
52+
}
53+
54+
// The root node is the bottom-most element in the stack
55+
while (st.size() > 1) {
56+
st.pop();
57+
}
58+
59+
return st.top();
60+
}
61+
};

0 commit comments

Comments
 (0)