我们从二叉树的根节点 root 开始进行深度优先搜索。
在遍历中的每个节点处,我们输出 D 条短划线(其中 D 是该节点的深度),然后输出该节点的值。(如果节点的深度为 D,则其直接子节点的深度为 D + 1。根节点的深度为 0)。
如果节点只有一个子节点,那么保证该子节点为左子节点。
给出遍历输出 S,还原树并返回其根节点 root。
示例 1:
输入:"1-2--3--4-5--6--7"
输出:[1,2,5,3,4,6,7]
class Solution {
public:
vector<pair<int,int>> vect;
int idx = 0, curD;
TreeNode* recoverFromPreorder(string s) {
while(idx < s.size()){ // 先对输入字符串进行处理
int cnt = 0;
string ans = "";
while (idx < s.size() && s[idx] == '-'){
cnt ++;
idx++;
}
while(idx < s.size() && s[idx] >= '0' && s[idx] <= '9'){
ans += s[idx++];
}
vect.push_back({cnt, stoi(ans)});
}
idx = 0;
return build(0);
}
TreeNode* build(int level){
if (idx >= vect.size()) return NULL;
TreeNode* root = new TreeNode(vect[idx].second);
if (++idx >= vect.size()) curD = INT_MAX;
else curD = vect[idx].first; // 往后看一个节点的深度,如果深度大于当前节点,则是子节点,否则回溯。
if (curD > level)
root->left = build(curD);
if (curD > level)
root->right = build(curD);
return root;
}
};