二叉树的创建和遍历

/*-----------------------------
Mission:
1.建立二叉树,输入^表示空节点。
2.遍历二叉树,打印所在层数
-----------------------------*/

#include <iostream>
#include <stdio.h>

using namespace std;

struct binTreeNode
{
    char data;
    binTreeNode *lchildren;
    binTreeNode *rchildren;
};

//前序创建
void creatBinTreePre(binTreeNode *&T)
{
     char c;
     c = getchar();
     if('^' == c)
        T = NULL;
     else{
        T = new binTreeNode;
        T->data = c;
        creatBinTreePre(T->lchildren);
        creatBinTreePre(T->rchildren);
    }
}

//前序遍历
void preorder(binTreeNode *T, int level)
{
     if(T){
        cout<<T->data<<" in level "<<level<<".\n";
        preorder(T->lchildren,level+1);
        preorder(T->rchildren,level+1);
     }
}

//中序遍历
void inorder(binTreeNode *T, int level)
{
     if(T){
        inorder(T->lchildren,level+1);
        cout<<T->data<<" in level "<<level<<".\n";
        inorder(T->rchildren,level+1);
     }
}

//后序遍历
 void postorder(binTreeNode *T, int level)
{
     if(T){
        postorder(T->lchildren,level+1);
        postorder(T->rchildren,level+1);
        cout<<T->data<<" in level "<<level<<".\n";
     }
}

 int main()
 {
     binTreeNode *T = NULL;
     creatBinTreePre(T);

     preorder(T,1);
     cout<<endl;

     inorder(T,1);
     cout<<endl;

     postorder(T,1);
     cout<<endl;

     return 0;
}


你可能感兴趣的:(二叉树的创建和遍历)