Last active
May 27, 2024 18:53
-
-
Save ObserverHerb/710003147c0410ed508875ba788bfde2 to your computer and use it in GitHub Desktop.
For populating test cases for those LeetCode problems with binary trees
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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