Skip to content

Commit 8efd632

Browse files
AhmedMorsy95haoel
authored andcommitted
recoverTreeFromPreorderTraversal.cpp
1 parent 8a1623e commit 8efd632

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
// source : https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/
2+
// Author Ahmed Morsy
3+
// Date : 2019-5-19
4+
5+
/**********************************************************************************
6+
*We run a preorder depth first search on the root of a binary tree.
7+
*At each node in this traversal, we output D dashes (where D is the depth of this node),
8+
*then we output the value of this node.
9+
*(If the depth of a node is D, the depth of its immediate child is D+1.The depth of the root node is 0.)
10+
*If a node has only one child, that child is guaranteed to be the left child.
11+
*Given the output S of this traversal, recover the tree and return its root.
12+
13+
* Input: "1-2--3--4-5--6--7"
14+
* Output: [1,2,5,3,4,6,7]
15+
16+
* Proposed Solution
17+
-----------------
18+
1. for each node in the input save its depth and value
19+
2. start a stack with the root node pushed onto it
20+
21+
IF the following node has the root's depth + 1 and the root has less than 2 children then this node
22+
is a child for this root. Add it to the stack.
23+
24+
ELSE then pop the current node from the stack.
25+
26+
**********************************************************************************/
27+
28+
/* Definition for a binary tree node.
29+
struct TreeNode {
30+
int val;
31+
TreeNode *left;
32+
TreeNode *right;
33+
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
34+
};
35+
*/
36+
37+
38+
class Solution {
39+
public:
40+
41+
TreeNode* recoverFromPreorder(string S) {
42+
vector<int>values,depth;
43+
int cur_val = 0 , cur_depth = 0;
44+
bool dash = false;
45+
for(char s : S){
46+
if(s == '-'){
47+
if(!dash){
48+
values.push_back(cur_val);
49+
depth.push_back(cur_depth);
50+
cur_depth = 0;
51+
cur_val = 0;
52+
}
53+
dash = true;
54+
cur_depth++;
55+
}
56+
else{
57+
dash = false;
58+
cur_val *= 10;
59+
cur_val += s-'0';
60+
}
61+
}
62+
values.push_back(cur_val);
63+
depth.push_back(cur_depth);
64+
65+
unordered_map<TreeNode*,int>depths;
66+
67+
68+
int ptr = 1;
69+
TreeNode *root = new TreeNode(values[0]);
70+
depths[root] = 0;
71+
stack<TreeNode*>st;
72+
st.push(root);
73+
74+
while(ptr < (int)values.size()){
75+
TreeNode *cur = st.top();
76+
if(depth[ptr] == depths[cur]+1 && (cur->left == NULL || cur->right == NULL)){
77+
TreeNode *t = new TreeNode(values[ptr++]);
78+
depths[t] = depths[cur]+1;
79+
if(cur->left == NULL){
80+
cur->left = t;
81+
}
82+
else{
83+
cur->right = t;
84+
}
85+
st.push(t);
86+
}
87+
else{
88+
st.pop();
89+
}
90+
}
91+
return root;
92+
93+
}
94+
};
95+

0 commit comments

Comments
 (0)