Skip to content

Instantly share code, notes, and snippets.

@ObserverHerb
Last active May 27, 2024 18:53
Show Gist options
  • Save ObserverHerb/710003147c0410ed508875ba788bfde2 to your computer and use it in GitHub Desktop.
Save ObserverHerb/710003147c0410ed508875ba788bfde2 to your computer and use it in GitHub Desktop.
For populating test cases for those LeetCode problems with binary trees
#include <type_traits>
#include <concepts>
#include <vector>
#include <optional>
#include <iostream>
template <typename T>
struct TreeNodeGeneric
{
T val;
TreeNodeGeneric *left;
TreeNodeGeneric *right;
TreeNodeGeneric() requires std::integral<T> : val(0), left(nullptr), right(nullptr) {}
TreeNodeGeneric(T val) : val(val), left(nullptr), right(nullptr) {}
TreeNodeGeneric(T val, TreeNodeGeneric *left, TreeNodeGeneric *right) : val(val), left(left), right(right) {}
};
template <typename T>
void Populate(const std::vector<std::optional<T>> &values,std::vector<TreeNodeGeneric<T>*> level,int index)
{
if (index == 0) level.at(0)->val=*values.at(index);
std::vector<TreeNodeGeneric<T>*> nextLevel;
try
{
for (TreeNodeGeneric<T> *node : level)
{
node->left=values.at(++index) ? new TreeNodeGeneric<T>(*values.at(index)) : nullptr;
nextLevel.push_back(node->left);
node->right=values.at(++index) ? new TreeNodeGeneric<T>(*values.at(index)) : nullptr;
nextLevel.push_back(node->right);
}
}
catch (const std::out_of_range &exception) {}
if (index < values.size()-1) Populate(values,nextLevel,index);
}
template <typename T>
void Populate(const std::vector<std::optional<T>> &values,TreeNodeGeneric<T>* root)
{
Populate(values,{root},0);
}
using TreeNode=TreeNodeGeneric<int>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment