名词解释
度数(degree) 一个结点的子树个数
树叶(leaf) 没有子树的结点称为树叶或终端结点
分支结点(branch node) 非终端结点
子女(child)和儿子(son)非终端结点
父母(parent)若结点s是结点p的儿子 则称p是x的父母或者父亲
有序树(ordered tree) 树中各个结点的儿子都是有序的
层数(level) 定义树根的层数为1.其他结点的层数等于其父母结点的层数加1
高度(height) 树中的结点的最大层数 规定空树的高度为 0
1.二叉树概念
二叉树由结点的有限集合构成,这个有限集合或者为空或者由一个根结点以及两颗不想交的分别称为这个根的左子树和右子树的二叉树组成
2.二叉树的遍历
binarytreenode.h
struct binaryTreeNode
{
ElementType data;
struct binaryTreeNode *LeftChild,*RightChild;
};
typedef struct binaryTreeNode BinaryTreeNode;
//初始化树节点
void InitBinaryTreeNode(BinaryTreeNode *btree,ElementType e,BinaryTreeNode *l,BinaryTreeNode *r)
{
btree->LeftChild=l;
btree->RightChild=r;
btree->data=e;
}
//生成树节点
BinaryTreeNode *CreateBTreeNode(ElementType item,BinaryTreeNode *lptr,BinaryTreeNode *rptr)
{
BinaryTreeNode *p;
p=(BinaryTreeNode *)malloc(sizeof(BinaryTreeNode));
if(p==NULL)
{
printf("memory allocation failure\n");
}
else
{
InitBinaryTreeNode(p,item,lptr,rptr);
}
}
binarytree.h
//此处声明要放在头部
enum boolean {FALSE,TRUE};
typedef enum boolean Bool;
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif
struct binaryTree
{
BinaryTreeNode *root;
};
typedef struct binaryTree BinaryTree;
//初始化
void InitBinaryTree(BinaryTree * bt)
{
bt->root=NULL;
}
Bool IsEmpty(BinaryTree *bt)
{
return ((bt->root) ? FALSE : TRUE);
}
Bool getRoot(BinaryTree *bt,ElementType *x)
{
if(bt->root)
{
*x=bt->root->data;
return TRUE;
}
else
{
return FALSE;
}
}
BinaryTreeNode *MakeTree(BinaryTree *bt,ElementType element,BinaryTreeNode *left,BinaryTreeNode *right)
{
bt->root=(BinaryTreeNode *)malloc(sizeof(BinaryTreeNode));
if(bt->root==NULL)
{
printf("Memory allocation failure!\n");
exit(1);
}
InitBinaryTreeNode(bt->root,element,left,right);
return bt->root;
}
//前序遍历
void PreOrder(BinaryTreeNode *t)
{
if(t)
{
//前序遍历 的先后顺序
printf("%c",t->data);
PreOrder(t->LeftChild); // a b d e
PreOrder(t->RightChild); // c f
}
}
//中序遍历
void InOrder(BinaryTreeNode *t)
{
if(t)
{
InOrder(t->LeftChild);
printf("%c",t->data);
InOrder(t->RightChild);
}
}
//后序遍历
void PostOrder(BinaryTreeNode *t)
{
if(t)
{
PostOrder(t->LeftChild);
PostOrder(t->RightChild);
printf("%c",t->data);
}
}
main.c
typedef char ElementType;
#include <stdio.h>
#include <stdlib.h>
#include "binarytreenode.h"
#include "binarytree.h"
int main()
{
BinaryTree *t=(BinaryTree *)malloc(sizeof(BinaryTree));
BinaryTreeNode *a,*b,*c,*d,*e,*f;
f=MakeTree(t,'f',NULL,NULL);
e=MakeTree(t,'e',NULL,NULL);
d=MakeTree(t,'d',NULL,NULL);
c=MakeTree(t,'c',f,NULL);
b=MakeTree(t,'b',d,e);
a=MakeTree(t,'a',b,c);
printf("The PreOrder is \n");
PreOrder(t->root);
printf("\n");
printf("The InOrder is \n");
InOrder(t->root);
printf("\n");
printf("The PostOrder is \n");
PostOrder(t->root);
printf("\n");
//getchar();
return 1;
}