正在加载……
专注、离线、切勿分心
建立一个二叉树,输入字符 '#' 表示该根结点为空,建二叉树采用递归思想,
  1、先输入根结点
  2、输入左子树
  3、输入右子树
其中第二步和第三步转去从第一步开始,直到输入流耗尽
  输入过程就是ab##c##     输入过程就是ABC###DE##F##
图一:
前序遍历:abc
中序遍历:bac
后序遍历:bca
图二:
前序遍历:ABCDEF
中序遍历:CBAEDF
后序遍历:CBEFDA
//二叉树
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
typedef struct BinaryTreeNode  //二叉树结点数据结构
{
        char data; 
        struct BinaryTreeNode* lchild;
        struct BinaryTreeNode* rchild;
}BTNode,*pBTNode;

//创建一个二叉树
int createBinaryTree(pBTNode& root);

//二叉树的三种遍历
void preorderTraversal(pBTNode& root);  //前序遍历,根左右
void inorderTraversal(pBTNode& root);  //中序遍历,左根右
void postorderTraversal(pBTNode& root);  //后序遍历,左右根

int createBinaryTree(pBTNode& root)
{
        char data;
        if(cin>>data)  //不能是while, 不然递归一直再while循环,直到流错误
        {
                if('#'==data)  //如果输入数据字符为‘#’表示根结点为空
                        root = NULL;
                else
                {
                        root = new BTNode();
                        root->data = data;
                        createBinaryTree(root->lchild);  //递归建立左子树
                        createBinaryTree(root->rchild);  //递归建立右子树
                }
        }
        return 0;
}
void preorderTraversal(pBTNode& root)
{
        if(NULL==root)
                return ;
        cout<<root->data<<" ";  //前序遍历输出根结点数据
        preorderTraversal(root->lchild);  //前序遍历左子树
        preorderTraversal(root->rchild);  //前序遍历右子树
}
void inorderTraversal(pBTNode& root)
{
        if(NULL==root)
                return ;
        inorderTraversal(root->lchild);  //中序遍历左子树
        cout<<root->data<<" ";  //中序遍历输出根结点数据
        inorderTraversal(root->rchild);  //中序遍历右子树
}
void postorderTraversal(pBTNode& root)
{
        if(NULL==root)
                return ;
        postorderTraversal(root->lchild);  //后序遍历左子树
        postorderTraversal(root->rchild);  //后序遍历右子树
        cout<<root->data<<" ";  //后序遍历输出根结点数据
}
int main()
{
        do{
                BTNode* root;  //给定一个根结点指针
                createBinaryTree(root);
                cout<<"preorder traversal:"<<endl;
                preorderTraversal(root);
                cout<<endl<<endl;

                cout<<"inorder traversal:"<<endl;
                inorderTraversal(root);
                cout<<endl<<endl;;

                cout<<"postorder traversal:"<<endl;
                postorderTraversal(root);
                cout<<endl<<endl;;
        }while(cout<<"continue?(Y/N):",fflush(stdin),getchar()=='Y');
        system("pause");
}
posted on 2018-06-21 16:38  正在加载……  阅读(162)  评论(0编辑  收藏  举报