二叉树的建立和遍历

来源:互联网 发布:网络电视直播在线看 编辑:程序博客网 时间:2024/06/07 19:11

建立二叉树

#pragma once#include <iostream>#include <stdlib.h>#include <assert.h>#include <stack>#include <queue>using namespace std;template <class T>struct BinaryTreeNode{    BinaryTreeNode<T>* _left;    BinaryTreeNode<T>* _right;    T _data;    BinaryTreeNode(const T& x)    :_data(x)    , _left(NULL)    , _right(NULL)    {}};template <class T>class BinaryTree{    typedef BinaryTreeNode<T> Node;public:    //初始化    BinaryTree()        :_root(NULL)    {}    //构造    BinaryTree(T* arr, size_t _size, const T& invalid)    {        assert(arr);        size_t index = 0;        _root=_creatTree(arr, _size, index, invalid);    }    //拷贝构造    BinaryTree(BinaryTree<T>& x)    {        _root = _CopyBinaryTree(x._root);    }    //运算符重载:判断两个树是否相等    BinaryTree<T>& operator=(BinaryTree<T>& x)    {        if (*this != x)        {            Node* tmp = _CopyBinaryTree(x._root);            _Distory(_root);            _root = tmp;        }        return *this;    }    //析构    ~BinaryTree()    {        Distory();    }    //前序遍历(递归)    PrevOrder()    {        cout << "前序遍历二叉树/n";        _PrevOrder(_root)            cout << endl;    }    //中序遍历(递归)    InOrder()    {        _InOrder(_root);        cout << endl;    }    //后序遍历(递归)    //层序遍历    //前序遍历(非递归)    //中序遍历(非递归)    //后序遍历(非递归)protected:    Node* _creatTree(const T* arr, size_t size, const T& invalid, size_t index)    {        Node* root = NULL;        while (arr[index] != invalid&& index < size)        {            root = new Node(arr[index]);            root->_left = _creatTree(arr, size, invalid, ++index);            root->_right = _creatTree(arr, size, invalid, ++index);        }        return root;    }    void Distory()    {        _Distory(_root);        _root = NULL;    }    void _Distory(Node* root)    {        if (root == NULL)            return;        _Distory(root->_left);        _Distory(root->_right);        delete root;    }    //    Node* _CopyBinaryTree(Node* root)    {        if (root == NULL)        {            return 0;        }        Node* node = new Node(root->_data);        node->_left = _CopyBinaryTree(root->_left);        node->_right = _CopyBinaryTree(root->_right);        return node;    }protected:    Node *_root;};

关于遍历和节点查找明天再写啦

原创粉丝点击