-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathRecover a Tree From Preorder Traversal.cpp
71 lines (54 loc) · 2 KB
/
Recover a Tree From Preorder Traversal.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
Solution by Rahul Surana
***********************************************************
We run a preorder depth-first search (DFS) on the root of a binary tree.
At each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node. 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.
If a node has only one child, that child is guaranteed to be the left child.
Given the output traversal of this traversal, recover the tree and return its root.
***********************************************************
*/
#include <bits/stdc++.h>
/**
* 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:
map<int,TreeNode*> m;
void dfs(string s){
int i = 0;
string y = "0";
while(i < s.length() && s[i] >= '0' && s[i] <= '9') y+=s[i++];
int b = stoi(y);
TreeNode* root = new TreeNode(b);
m[0] = root;
while(i < s.length()){
int curr = 0;
while(s[i++] == '-') {curr++;}
i--;
string x = "";
while(i < s.length() && s[i] >= '0' && s[i] <= '9') x+=s[i++];
int z = stoi(x);
TreeNode* a = new TreeNode(z);
// cout << curr <<" "<< z <<"\n";
if( m[curr-1] && m[curr-1]->left != NULL) {
m[curr-1]->right = a;
}
else{
m[curr-1]->left = a;
}
m[curr] = a;
}
}
TreeNode* recoverFromPreorder(string traversal) {
dfs(traversal);
return m[0];
}
};