leetcode 1028. Recover a Tree From Preorder Traversal

2 篇文章 0 订阅

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 and 1000.
  • Each node will have a value between 1 and 10^9.

总是忘了要添加边界条件 ;

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* recoverFromPreorder(string S) 
    {
        int i = 0 ; 
        return recoverFromPreorder(0 , i , S) ;
    }
    
private :
    
    TreeNode* recoverFromPreorder(int depth , int& i , string S)
    {
        if(i >= S.size()) return NULL ;
        int j = i ;
        int r_depth = getdepth(j , S) ;
        int num = getnum(j , S) ;
        if(r_depth != depth) return NULL ;
        i = j ;
        TreeNode* v = new TreeNode(num) ;
        v->left = recoverFromPreorder(depth + 1 , i , S) ;
        v->right = recoverFromPreorder(depth + 1 , i , S) ;
        return v ;
    }
    
    int getdepth(int& i , string S)
    {
        int j = i ;
        while(i < S.size() && S[i] == '-') i++ ;
        return i - j ;
    }
    
    int getnum(int &i , string S)
    {
        int j = i ;
        while(i < S.size() && isdigit(S[i])) i++ ;
        return i > j ? stoi(S.substr(j , i - j)) : 0;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值