线性表(不管是顺序存储还是链式存储)的元素之间的逻辑关系是线性的,这有时候并不能满足实际的要求,树形结构是另一种数据结构,它的元素之间的逻辑关系画成图的话形似一颗倒挂的树,故而得名。二叉树是树形结构中的特例,每个结点最多有两个孩子,就好像处于计划生育年代一样。
下面就是二叉树的一些基本操作,程序是用c语言写的。
#include <stdio.h> #include <stdlib.h> typedef struct _Node { int data; struct _Node *lchild, *rchild; } Node, *Pnode; Pnode CreateBT(); void Preorder(Pnode); void Inorder(Pnode); void Postorder(Pnode); void ShowTree(Pnode, int); int LeafNum(Pnode); int NodeNum(Pnode); int main() { Pnode head = NULL; int x = 0; printf("二叉树\n"); do { printf("*************************\n"); if (head) { printf("(二叉树已存在!)\n"); } else { printf("(二叉树还未创建!)\n"); } printf("* 请选择要执行的操作:\n"); printf("* [1] 创建二叉树\n"); printf("* [2] 先序遍历\n"); printf("* [3] 中序遍历\n"); printf("* [4] 后续遍历\n"); printf("* [5] 显示二叉树\n"); printf("* [6] 显示叶子数\n"); printf("* [7] 显示二叉树的结点数\n"); printf("* [9] 退出\n"); printf("*************************\n"); printf("你的选择:"); scanf("%d", &x); switch (x) { case 1: printf("请输入根结点\n"); head = CreateBT(); break; case 2: Preorder(head); printf("\n"); break; case 3: Inorder(head); printf("\n"); break; case 4: Postorder(head); printf("\n"); break; case 5: ShowTree(head, 1); break; case 6: printf("叶子数是%d\n", LeafNum(head)); break; case 7: printf("结点数是%d\n", NodeNum(head)); break; default: break; } } while (x != 9); printf("bye!\n"); return 0; } Pnode CreateBT() { Pnode t = NULL; int iput = 0; scanf("%d", &iput); if (iput==0) { t = NULL; } else { t = (Pnode)malloc(sizeof(Node)); t->data = iput; printf("请输入%d的左孩子\n", iput); t->lchild = CreateBT(); printf("请输入%d的右孩子\n", iput); t->rchild = CreateBT(); } return t; } void Preorder(Pnode p) { if (p) { printf("%d ", p->data); Preorder(p->lchild); Preorder(p->rchild); } } void Inorder(Pnode p) { if (p) { Inorder(p->lchild); printf("%d ", p->data); Inorder(p->rchild); } } void Postorder(Pnode p) { if (p) { Postorder(p->lchild); Postorder(p->rchild); printf("%d ", p->data); } } void ShowTree(Pnode p, int dep) { if (p) { for (int i = 0; i < dep; i++) { printf(" "); } printf("%d**********\n", p->data); ShowTree(p->lchild,dep+1); ShowTree(p->rchild, dep+1); } } int LeafNum(Pnode p) { if ((!p->lchild) && (!p->rchild)) { return 1; } else if (!p->lchild) { return LeafNum(p->rchild); } else if (!p->rchild) { return LeafNum(p->lchild); } else { return LeafNum(p->lchild)+LeafNum(p->rchild); } } int NodeNum(Pnode p) { if (!p) { return 0; } return NodeNum(p->lchild) + NodeNum(p->rchild)+1; }