1028. Recover a Tree From Preorder Traversal(Leetcode每日一題-2020.06.18)

Problem

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.

Example1

Input: “1-2–3--4-5–6--7”
Output: [1,2,5,3,4,6,7]

在這裏插入圖片描述

Example2

Input: “1-2–3—4-5–6—7”
Output: [1,2,5,3,null,6,null,4,null,7]

在這裏插入圖片描述

Example3

Input: “1-401–349—90–88”
Output: [1,401,null,349,88,90]
在這裏插入圖片描述

Solution

不會做!

class Solution {
public:
    TreeNode* recoverFromPreorder(string S) {
        stack<TreeNode*> path;
        int pos = 0;
        while (pos < S.size()) 
        {
            int level = 0;
            while (S[pos] == '-') {
                ++level;
                ++pos;
            }
            int value = 0;
            while (pos < S.size() && isdigit(S[pos])) 
            {
                value = value * 10 + (S[pos] - '0');
                ++pos;
            }
            TreeNode* node = new TreeNode(value);
            if (level == path.size()) 
            {
                if (!path.empty()) 
                {
                    path.top()->left = node;
                }
            }
            else 
            {
                while (level != path.size()) 
                {
                    path.pop();
                }
                path.top()->right = node;
            }
            path.push(node);
        }
        while (path.size() > 1) 
        {
            path.pop();
        }
        return path.top();
    }
};

Ref

https://leetcode-cn.com/problems/recover-a-tree-from-preorder-traversal/solution/shou-hui-tu-jie-fei-di-gui-fa-zhong-gou-chu-er-cha/

https://leetcode-cn.com/problems/recover-a-tree-from-preorder-traversal/solution/cong-xian-xu-bian-li-huan-yuan-er-cha-shu-by-leetc/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章