Leet Code Daily 2024-07-15 - Create Binary Tree From Descriptions
Code
● ● ●c++/**
* 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) {}
* };
*/
constexpr int kMaxSize = 100000;
class Solution {
public:
TreeNode* createBinaryTree(vector<vector<int>>& descriptions) {
vector<TreeNode*> nodes(kMaxSize, nullptr);
auto getNode = [&](const int val) {
if (nodes[val - 1] == nullptr) {
nodes[val - 1] = new TreeNode(val);
}
return nodes[val - 1];
};
vector<bool> isRoot(kMaxSize, true);
for (const auto desc : descriptions) {
auto parent = getNode(desc[0]);
if (desc[2] == 1) {
parent->left = getNode(desc[1]);
} else {
parent->right = getNode(desc[1]);
}
isRoot[desc[1] - 1] = false;
}
for (int i = 0; i < kMaxSize; i++) {
if (isRoot[i] && nodes[i] != nullptr) {
return nodes[i];
}
}
return nullptr;
}
};