LC1028. ecover a Tree From Preorder Traversal

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

  • 솔직히 왜 Hard인지 모르겠.. 여튼 평이한 DFS 문제.
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
/**
 * 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:
    string str;
    int value = -1;
    int depth = -1;
    int cur = 0;
    void next() {
        if(cur >= str.size()) return;
        depth = 0;
        while(str[cur] == '-') depth++, cur++;
        value = 0;
        while(isdigit(str[cur]))
            value = value*10 + str[cur++] - '0';
    }
    
    TreeNode* dfs(int lv) {
        if(value == -1) next();
        TreeNode* node;
        if(depth == lv) {
            node = new TreeNode(value);
            value = -1;
            depth = -1;
        } else return nullptr;
        
        node->left = dfs(lv+1);
        node->right = dfs(lv+1);
        return node;
    }
    
    TreeNode* recoverFromPreorder(string S) {
        str = S;
        return dfs(0);
    }
};