【刷leetcode,拿Offer-039】1028. Recover a Tree From Preorder Traversal

题目链接: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:

【刷leetcode,拿Offer-039】1028. Recover a Tree From Preorder Traversal_第1张图片

Input: "1-2--3--4-5--6--7"
Output: [1,2,5,3,4,6,7]

Example 2:

【刷leetcode,拿Offer-039】1028. Recover a Tree From Preorder Traversal_第2张图片

Input: "1-2--3---4-5--6---7"
Output: [1,2,5,3,null,6,null,4,null,7]

 

Example 3:

【刷leetcode,拿Offer-039】1028. Recover a Tree From Preorder Traversal_第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 and 1000.
  • Each node will have a value between 1 and 10^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;ileft=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=0;i--){
            val+=(t3[i]-'0')*tt;
            tt*=10;
        }
        res->val=val;
        return res;
    }
};

 

你可能感兴趣的:(LeetCode,Offer,面试)