二叉树创建及遍历
#include <iostream>
using namespace std;
typedef char DataType;
//二叉树数据结构
struct node
{
DataType info ; //存放结点数据
struct node *lchild , *rchild ; //指向左右孩子的指针
};
typedef struct node *BiTree ;
/*创建二叉树
函数名:createBiTree
参数:无
返回值:二叉树根结点指针
*/
BiTree createBiTree(void)
{
//请在此处填写代码, 完成二叉树和创建,返回值是二叉树的根结点指针
/********** Begin **********/
char ch; //定义一个字符变量
BiTree root; //二叉树根的类型
cin>>ch; //输入一个数据,把他保存在ch所在储存位置
if(ch=='#') root=NULL;
else{
root=new struct node; //给树的节点开辟空间
root->info=ch; //root指向的结构体里面的data成员变量,给这个变量赋值ch
root->lchild=createBiTree(); //创建左子树
root->rchild=createBiTree(); //创建右子树
}
return root;
/********** End *********/
}
void visit(BiTree T) //输出结点T的数据
{
cout<<T->info ; //输出T这个节点的info值,也就是数据值
}
void inOrder(BiTree root)
{
if(root == NULL) return ;
inOrder(root->lchild);
visit(root);
inOrder(root->rchild);
}
int main(void)
{
BiTree root = createBiTree();
inOrder(root);
}