【資料結構】建立二叉樹的方法

pengfoo發表於2012-10-05

建立普通二叉樹的方法:

具體可以看程式碼:

//交談中請勿輕信匯款、中獎資訊、陌生電話,勿使用外掛軟體。
//

#include <iostream>
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);
}


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

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


 

相關文章