Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template<typename Type>
- class BinaryTree {
- public:
- struct Node {
- Type data;
- Node* left{ nullptr };
- Node* right{ nullptr };
- Node(Type && value) : data{ std::move(value) } { }
- Node() = delete;
- };
- BinaryTree() noexcept { }
- BinaryTree(BinaryTree const &) = delete;
- BinaryTree(BinaryTree &&rhs) : root(rhs.root) { }
- BinaryTree& operator=(BinaryTree rhs) {
- using std::swap;
- swap(root, rhs.root);
- return *this;
- }
- ~BinaryTree() {
- reset();
- }
- // head, left leaf, right leaf
- // value type, tree will not be modified
- void preOrderTraversal(std::function<void(Type)> visit) {
- if( nullptr == root ) return;
- std::stack<Node*> stack;
- stack.push(root);
- while( !stack.empty() ) {
- auto node = stack.top();
- stack.pop();
- visit(node->data);
- if( node->right ) {
- stack.push(node->right);
- }
- if( node->left ) {
- stack.push(node->left);
- }
- }
- }
- // reference type, tree will be modified; so the tree need update order of nodes.
- void preOrderTraversal(std::function<void(Type&)> visit) {
- if( nullptr == root ) return;
- std::stack<Node*> stack;
- stack.push(root);
- while( !stack.empty() ) {
- auto node = stack.top();
- stack.pop();
- visit(node->data);
- if( node->right ) {
- stack.push(node->right);
- }
- if( node->left ) {
- stack.push(node->left);
- }
- }
- update(); // some update function keep the tree in binary search tree order.
- }
- private:
- Node* root{nullptr};
- }
- // just as an example, readonly can not change the tree,
- // while write may change the tree
- void readonly(double value) {
- std::cout <<value++ << std::endl;
- }
- void write(Type & value) {
- std::cout <<value++ << std::endl;
- }
- int main() {
- BinaryTree<double> btree;
- // ... working on the tree..., push, pop, etc.
- btree.preOrderTraversal(readonly);
- btree.preOrderTraversal(write);
- }
Add Comment
Please, Sign In to add comment