[LeetCode] Recover a Tree From Preorder Traversal

1028. Recover a Tree From Preorder Traversal

We run a preorder depth-first search (DFS) 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 traversal of this traversal, recover the tree and return its root.

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
/**
* 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 {
int parseValue(string& t, int& pos) {
int res = 0;
for(; pos < t.length() && '0' <= t[pos] && t[pos] <= '9'; pos++) {
res = (res<<3) + (res<<1) + (t[pos] & 0b1111);
}
return res;
}
bool hasChild(string& t, int pos, int target) {
if(pos + target >= t.length()) return false;
for(int i = pos; i < pos + target ; i++) {
if(t[i] != '-') return false;
}
return true;
}
TreeNode* parseTree(string& t, int& pos, int depth) {
if(t.length() <= pos)
return nullptr;
TreeNode* node = new TreeNode(parseValue(t, pos));
if(hasChild(t, pos, depth)) {
pos += depth;
node->left = parseTree(t, pos, depth + 1);

if(hasChild(t, pos, depth)) {
pos += depth;
node->right = parseTree(t, pos, depth + 1);
}
}
return node;
}
public:
TreeNode* recoverFromPreorder(string traversal) {
int pos = 0;
return parseTree(traversal, pos, 1);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/23/PS/LeetCode/recover-a-tree-from-preorder-traversal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.