樹的定義:
樹是n個結點的有限集。 n=O 時稱爲空樹。 在任意-棵非空樹中: ( 1 )有且僅有一·個特定的根結點: (2)若干子樹(互不相交)
樹的定義是遞歸定義的
二叉樹( Binary Tree) 是 n個結點的有限集合,該集合或者爲空集(稱爲空二叉樹),戴者由一個根結點和兩顆互不相交的、分別稱爲根結點的左子樹和右子樹的二叉樹組成 。
二叉樹結點的定義:
typedef char elemtype;
typedef struct BtNode
{
elemtype data;
BtNode *leftchild;
BtNode *rightchild;
}BtNode,*BinaryTree;
下圖二叉樹的遍歷:
先根遍歷: ABCDEFGH
中根遍歷:CBEDFAGH
後根遍歷 : CEFDBHGA
二叉樹的創建:
BtNode * creat_tree()
{
elemtype x;
cin>>x;
BtNode *p = NULL;
if (x != '#')
{
p = Buynode();
p->data = x;
p->leftchild = creat_tree();
p->rightchild = creat_tree();
}
return p;
}
字符'#'表示左孩子或右孩子爲空。先創建根結點,在遞歸創建左子樹和右子樹
二叉樹遍歷:
//先序遍歷二叉樹
void PreOrder(BtNode *ptree)
{
if (ptree != NULL)
{
cout<<ptree->data<<" ";
PreOrder(ptree->leftchild);
PreOrder(ptree->rightchild);
}
}
//中序遍歷二叉樹
void InOrder(BtNode *ptree)
{
if (ptree != NULL)
{
InOrder(ptree->leftchild);
cout<<ptree->data<<" ";
InOrder(ptree->rightchild);
}
}
//後序遍歷二叉樹
void PastOrder(BtNode *ptree)
{
if (ptree != NULL)
{
PastOrder(ptree->leftchild);
PastOrder(ptree->rightchild);
cout<<ptree->data<<" ";
}
}
測試代碼:
void main()
{
BinaryTree tree1;
tree1 = creat_tree();
PreOrder(tree1);
cout<<endl;
InOrder(tree1);
cout<<endl;
PastOrder(tree1);
}
測試結果如圖: