Untitled
unknown
plain_text
a year ago
1.6 kB
1
Indexable
Never
#include <iostream> #include <vector> #include <queue> template <typename T> struct TreeNode { TreeNode<T>* left; TreeNode<T>* right; T value; TreeNode(T n_value = 0, TreeNode<T>* n_left = nullptr, TreeNode<T> *n_right = nullptr) : left{n_left}, right{n_right}, value{n_value} {} inline bool has_free_leaves() { return !(right && left); } }; template <typename T> class Tree { public: TreeNode<T>* root; Tree(): root{nullptr} {} Tree(TreeNode<T> *node): root{node} {} template <typename lambda> TreeNode<T>* BFS(lambda criteria) { std::queue<TreeNode<T>*> q; q.push(root); while(!q.empty()) { TreeNode<T>* current_node = q.front(); q.pop(); std::cout << current_node; if (criteria(current_node)) return current_node; if(current_node->left) q.push(current_node->left); if(current_node->right) q.push(current_node->right); } return nullptr; } void insert_node(TreeNode<T>* node) { TreeNode<T>* target = BFS( \ [](TreeNode<T>* n) -> bool \ {return n ? n->has_free_leaves() :0;} ); if(!target->left) {target->left = node; return;} if(!target->right) {target->right = node; return;} } void insert_value(T val) { insert_node(new TreeNode<T>(val)); } }; template <typename T> Tree<T> construct(std::vector<T> &arr) { Tree<T> ret; for (T x: arr) ret.insert_value(x); return ret; } int main() { std::vector<int> vect{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; Tree<int> t(new TreeNode<int>(69)); std::queue<TreeNode<int>*> q; q.push(t.root); construct(vect); }