1. 程式人生 > >C++二叉樹建立與遍歷

C++二叉樹建立與遍歷

注意:二叉樹建立時要用指標的引用,詳解參考:

#include <iostream>
using namespace std;

struct BiNode
{
	char data;
	BiNode *lchild, *rchild;
};

void CreateBiTree(BiNode* &T)	//注意:&的意思是傳進來節點指標的引用,目的是讓傳遞進來的指標發生改變
{
	char c;
	cin >> c;
	if ('#' == c)             //當遇到#時,令樹的根節點為NULL,從而結束該分支的遞迴
		T = NULL;
	else
	{
		T = new BiNode;
		T->data = c;
		CreateBiTree(T->lchild);
		CreateBiTree(T->rchild);
	}
}

void PreOrderTraverse(BiNode *T)		//引數為BiNode * &T也可以
{
	if (T)
	{
		cout << T->data << " ";
		PreOrderTraverse(T->lchild);
		PreOrderTraverse(T->rchild);
	}
}

void InOrderTraverse(BiNode *T)		
{
	if (T)
	{
		InOrderTraverse(T->lchild);
		cout << T->data << " ";
		InOrderTraverse(T->rchild);
	}
}

void PostOrderTraverse(BiNode *T)		
{
	if (T)
	{
		PostOrderTraverse(T->lchild);
		PostOrderTraverse(T->rchild);
		cout << T->data << " ";
	}
}

int main()
{
	BiNode *BiTree;					//宣告一個指向二叉樹根節點的指標        
	cout << "建立二叉樹,其中A~Z字元代表資料,用'#'表示空樹:" << endl;
	CreateBiTree(BiTree);
	cout << "建立二叉樹成功……" << endl;
	cout << "先序遍歷:" << endl;
	PreOrderTraverse(BiTree);
	cout << endl;
	cout << "中序遍歷:" << endl;
	InOrderTraverse(BiTree);
	cout << endl;
	cout << "後序遍歷:" << endl;
	PostOrderTraverse(BiTree);
	cout << endl;
	return 0;
}