Home LeetCode. 1028. Recover a Tree From Preorder Traversal
Post
Cancel

LeetCode. 1028. Recover a Tree From Preorder Traversal

image

[Link] https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <bits/stdc++.h>
/**
 * 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:
    vector<pair<int,int>> nodes;
    TreeNode* div_con(int l, int r) {
        if(l == r) return new TreeNode(nodes[l].first);
        else if(l+1 == r) {
            TreeNode *child_node = new TreeNode(nodes[r].first);
            return new TreeNode(nodes[l].first, child_node, nullptr);
        }
        int top_depth = nodes[l].second;
        vector<int> next_nodes;
        for(int i = l+1; i <= r; i++) {
            if(nodes[i].second == top_depth + 1) next_nodes.push_back(i);
        }
        if(next_nodes.size() == 1) {
            return new TreeNode(nodes[l].first, div_con(next_nodes[0], r), nullptr);
        } else if(next_nodes.size() == 2) {
            return new TreeNode(nodes[l].first,div_con(next_nodes[0], next_nodes[1] - 1), div_con(next_nodes[1], r));
        }
        return new TreeNode(nodes[l].first);
    }

    TreeNode* recoverFromPreorder(string s) {
        int i = 0, depth = 0, tot = 0;
        string str;
        while(i < s.size()) {
            depth = 0; str = "";
            while(s[i]=='-') { depth++; i++; }
            while(i < s.size() && s[i]!='-') str+=s[i++];
            int node_val = stoi(str);
            nodes.push_back({ node_val, depth });
            TreeNode* node = new TreeNode(node_val);
            tot++;
        }
        return div_con(0, tot - 1);
    }
};
This post is licensed under CC BY 4.0 by the author.