LeetCode 1028. 从先序遍历还原二叉树
原题链接
中等
作者:
大明湖的鱼
,
2021-02-01 18:26:00
,
所有人可见
,
阅读 352
/**
* 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:
//d用来存深度信息,v用来存节点值
TreeNode* build(queue<int>& d,queue<int>& v,int depth){
if(d.front() != depth) return nullptr;//说明不是当前的子树了
TreeNode* root = new TreeNode(v.front());
d.pop();
v.pop();
root->left = build(d,v,depth+1);
root->right = build(d,v,depth+1);
return root;
}
TreeNode* recoverFromPreorder(string S) {
int left = 0;//left为-的开始位置,i记录结束位置,记录深度
queue<int> d,v;
for(int i = 0;i < S.size();i++){
if(S[i] != '-'){ //不是 - 了
d.push(i-left);
left = i;
while(i < S.size() && S[i] !='-') i++;//确定数字长度
v.push(stoi(S.substr(left,i-left)));
left = i;
}
}
return build(d,v,0);
}
};