二叉树的创建与三种递归遍历
Posted lglbk
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树的创建与三种递归遍历相关的知识,希望对你有一定的参考价值。
#include<iostream>
struct tree
{
struct tree *left;
struct tree *right;
int data;
};
tree *T;
typedef struct tree *Tree,*TNode,TREE;
using namespace std;
void PreCreateTree(Tree& T);
void PreOrder(Tree& T);
void InOrder(Tree& T);
void PostOrder(Tree& T);
int main()
{
cout<<"输入现需创建二叉树的序列:"<<endl;
PreCreateTree(T);
cout<<"前序遍历结果为:";
PreOrder(T);
return 0;
cout<<endl;
cout<<"中序遍历结果为:";
InOrder(T);
cout<<endl;
cout<<"后序遍历结果为:";
PostOrder(T);
return 0;
}
void PreCreateTree(Tree& T)
{
int data;
cin >> data;
T = new tree;
if (data == -1)
{
T = NULL;
return;
}
T->left = NULL;
T->right = NULL;
T->data = data;
PreCreateTree(T->left);
PreCreateTree(T->right);
}
void PreOrder(Tree& T)
{
if(T==NULL)
return;
if (T)
{
cout << T->data;
PreOrder(T->left);
PreOrder(T->right);
}
}
void InOrder(Tree& T)
{
if (T)
{
InOrder(T->left);
cout << T->data ;
InOrder(T->right);
}else{
return;
}
}
void PostOrder(Tree& T)
{
if (T)
{
PostOrder(T->left);
PostOrder(T->right);
cout << T->data ;
}else{
return;
}
}
以上是关于二叉树的创建与三种递归遍历的主要内容,如果未能解决你的问题,请参考以下文章