4.23-树基本概念作业

题目要求

使用递归法创建一棵树,请参考PPT上相关算法实现。要求包含:
1.代码。2.运行结果截图。3.在该树上实现前、中、后序遍历。

1.代码展示

#include<iostream>
using namespace std;

struct BTNode//结构体定义
{
    char data;
    BTNode* L;//左孩子
    BTNode* R;//右孩子
};
void creatNode(BTNode* &T) //建立二叉树 
{
    char ch;
    cin >> ch;
    if (ch == '#')  // 按照一个二叉树的前序遍历输入若子节点为空就输入 #  
    {
	    T = NULL;
    }
    else
    {
	    T = new BTNode;
	    T->data = ch;
	    creatNode(T->L);
	    creatNode(T->R);
    }
}
void preOrder(BTNode* &T)//前序遍历 
{
    if (T == NULL)
	    return;
    else
    {
	    cout << T->data;
	    preOrder(T->L);
	    preOrder(T->R);
    }
}
void inOrder(BTNode* &T)//中序遍历
{
    if (T == NULL)
	    return;
    else
    {
	    inOrder(T->L);
	    cout << T->data;
	    inOrder(T->R);
    }
}

void posOrder(BTNode* &T)//后序遍历 
{
    if (T == NULL)
	    return;
    else
    {
	    posOrder(T->L);
	    posOrder(T->R);
	    cout << T->data;
    }

}
int main()
{
    BTNode* T;
    cout << "输入一个二叉树(按照这个二叉树的前序遍历输入,若子节点为空就输入“# ”):" << endl;
    creatNode(T);
    cout << "前序遍历:";
    preOrder(T);
    cout << endl;
    cout << "中序遍历:";
    inOrder(T);
    cout << endl;
    cout << "后序遍历:";
    posOrder(T);
    cout << endl;
    delete	T;
    system("pause");
}

2.运行结果截图

posted @ 2019-04-27 22:07  不速客  阅读(93)  评论(0)    收藏  举报