菜鸟变身记

导航

 
#include <iostream>
#include <malloc.h>
using namespace std;
typedef struct BiTNode
{
	char data;
	struct BiTNode *lchild,*rchild;

}BiTNode;

BiTNode *CreateBinTree ()
{
	char ch;
	//scanf("%c",&ch);
	cin>>ch;
	BiTNode *root = (BiTNode*)malloc(sizeof(BiTNode));//根节点

	if(ch=='#')
		root = NULL; //将相应指针置空
	else
	{
		root->data=ch;
		root->lchild=CreateBinTree(); //构造左子树
		root->rchild=CreateBinTree(); //构造右子树
	}

	return root;
}

void preOrder(BiTNode *root)
{
	if (root==NULL)
		return;

	cout<<root->data<<" ";
	preOrder(root->lchild);
	preOrder(root->rchild);
}

void inOrder(BiTNode *root)
{
	if (root==NULL)
		return;
    if (root->lchild) inOrder(root->lchild);
	cout<<root->data<<" ";
	if (root->rchild) inOrder(root->rchild);
}

void postOrder(BiTNode *root)
{
	if (root==NULL)
		return;
    postOrder(root->lchild);
	postOrder(root->rchild);
	cout<<root->data<<" ";
}


int main()
{
	BiTNode *root = NULL;
	cout<<"Please Input The Node:"<<endl;
	root = CreateBinTree();

	cout<<endl;
	cout<<"The PreOrder is:";
	preOrder(root);
	cout<<endl<<"The inOrder is:";
	inOrder(root);
	cout<<endl<<"The postOrder is:";
	postOrder(root);
	cout<<endl;
	return 0;
}

  测试结果:

 

posted on 2012-11-07 19:28  菜鸟变身记  阅读(132)  评论(0)    收藏  举报