1028: Recover-a-Tree-From-Preorder-Traversal
Hard
Very doable “Hard” question.
Key thing that I realised that, if I have a node of depth
n
, then the parent is always the
most recently defined node of depth n-1
(since we are
dealing with depth-first search).
Therefore, we can just store every node pointer inside an array, where its index is equal to its depth:
Code:
/**
* 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 {
private:
int returnInt(string& traversal, int& index) {
= "";
string stringNum while (index < traversal.size() && traversal[index] != '-') {
+= traversal[index];
stringNum ++index;
}
return stoi(stringNum);
}
int returnLayer(string& traversal, int& index) {
int layerNum = 0;
while (index < traversal.size() && traversal[index] == '-') {
++layerNum;
++index;
}
return layerNum;
}
public:
* recoverFromPreorder(string traversal) {
TreeNode* root = new TreeNode();
TreeNode<TreeNode*> depths;
vector.push_back(root);
depthsint index = 0;
-> val = returnInt(traversal, index);
root for (index; index < traversal.size(); index) {
int value = returnLayer(traversal, index);
* ptr = depths[value-1];
TreeNodeif (ptr -> left) {
-> right = new TreeNode(returnInt(traversal, index));
ptr if (depths.size() > value) {
[value] = ptr->right;
depths} else {
.push_back(ptr->right);
depths}
} else {
-> left = new TreeNode(returnInt(traversal, index));
ptr if (depths.size() > value) {
[value] = ptr->left;
depths} else {
.push_back(ptr->left);
depths}
}
}
return root;
}
};