题目链接:https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/
题面:
1028. Recover a Tree From Preorder Traversal
Hard
1625FavoriteShare
We run a preorder depth first search 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 S
of this traversal, recover the tree and return its root
.
Example 1:
Input: "1-2--3--4-5--6--7" Output: [1,2,5,3,4,6,7]
Example 2:
Input: "1-2--3---4-5--6---7" Output: [1,2,5,3,null,6,null,4,null,7]
Example 3:
Input: "1-401--349---90--88" Output: [1,401,null,349,88,90]
Note:
- The number of nodes in the original tree is between
1
and1000
. - Each node will have a value between
1
and10^9。
题意:给定一棵树的先序遍历的特殊表示,从该表示中还原出该树。(注意如果一个节点只有一个孩子,那么这个孩子一定是左儿子)。
解题:
根据-数,确定深度,递归划分字符串,到叶子节点则停止递归。(没想到,居然一遍过了,有点进步,嘻嘻)
代码:
class Solution {
public:
TreeNode* recoverFromPreorder(string S) {
int cnt=0,p1=-1,val=0,tt=1;
string t1,t2,t3;
TreeNode *res=new TreeNode(0);
for(int i=0;i<S.length();i++){
if(S[i]=='-')
cnt++;
else
{
for(int j=i;j<S.length();j++){
if(S[j]!='-')
continue;
else{
p1=j;
break;
}
}
if(p1!=-1){
int tmp=0,p2=-1;
for(int i=p1+1;i<S.length();i++){
if(S[i]=='-'){
tmp++;
}
else{
if(tmp==cnt+1)
{
p2=i-tmp;
break;
}
tmp=0;
}
}
if(p2==-1){
t1=S.substr(p1);
res->left=recoverFromPreorder(t1);
res->right=NULL;
}
else{
t1=S.substr(p1,p2-p1);
t2=S.substr(p2);
res->left=recoverFromPreorder(t1);
res->right=recoverFromPreorder(t2);
}
}
else{
res->left=res->right=NULL;
}
break;
}
}
for(int i=cnt;i<S.length();i++){
if(S[i]=='-')break;
else{
t3+=S[i];
}
}
for(int i=t3.length()-1;i>=0;i--){
val+=(t3[i]-'0')*tt;
tt*=10;
}
res->val=val;
return res;
}
};