二叉树的构建与遍历(最简单的二叉树)

#include <iostream>
using namespace std;

**//****定义节点的类模板。二叉树的节点是一个类的实例,该类由一个信息成员和两个指针成员组成*****
template <typename T>
class binaryTreeNode
{
public:
  T element;
  binaryTreeNode<T> *leftchild;
  binaryTreeNode<T> *rightchild;

  binaryTreeNode()
 {
    leftchild = NULL;
    rightchild = NULL;
 }
};

**//****递归地创建一颗二叉树(先序)**
template <typename T>
class binaryTree
{
public:
    binaryTree() {}
    binaryTreeNode<T> *create();
    void preTree(binaryTreeNode<T>*);
};
template <typename T>
binaryTreeNode<T>* binaryTree<T>::create()
{
    binaryTreeNode<T>* current = NULL;
    T val;
    cin>>val;
    if(val == -1)
        return NULL;//当前节点不存在
    else
    {
        current = new binaryTreeNode<T>;
        current->element = val;
        current->leftchild = create();

        current->rightchild = create();
        return current;
    }
}

**//****先序遍历二叉树并打印******
template <typename T>
void preTree(binaryTreeNode<T>* current)
{
      if(current)
      {
          cout<<current->element;
          preTree(current->leftchild);
          preTree(current->rightchild);
      }
}

**//****后序遍历二叉树******
template <typename T>
void proTree(binaryTreeNode<T>* current)
{
    if(current)
    {
        proTree(current->leftchild);
        proTree(current->rightchild);
        cout<<current->element;
    }
}

**//****中序遍历二叉树******
template <typename T>
void midTree(binaryTreeNode<T>* current)
{
    if(current)
    {
        midTree(current->leftchild);
        cout<<current->element;
        midTree(current->rightchild);
    }
}

int main()
{
    binaryTreeNode<int>* btd;
    binaryTree<int> bt;
    btd=bt.create();
    preTree(btd);
    cout<<endl;
    proTree(btd);
    cout<<endl;
    midTree(btd);
    cout<<endl;
}

结果:

/home/yhj/测试程序/数据结构与算法/二叉树/cmake-build-debug/aa
1 2 -1 -1 3 -1 -1
123
231
213

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/gyhjlauy/article/details/89222062