#ifndef _BI_NODE_ #define _BI_NODE_ typedef struct _binode { char data; struct _binode *lchild, *rchild; }BiNode; #endif // !_BI_NODE_
#ifndef _TREE_OP_ #define _TREE_OP_ void createBiTree(BiNode **T); void preorderTraverse(BiNode *T); void InorderTraverse(BiNode *T); void postorderTraverse(BiNode *T); int LeafCount(BiNode *T); int Hight(BiNode *T); #endif // !_TREE_OP_
#include <stdio.h> #include <stdlib.h> #include "BiNode.h" //前序创建二叉树 void createBiTree(BiNode **T) { //这里用了指针的指针,如果只用一维指针的话,则无法创建 char ch; scanf("%c", &ch); if (ch == '#') { *T = NULL; } else { *T = (BiNode *)malloc(sizeof(BiNode)); (*T)->data = ch; createBiTree(&((*T)->lchild)); createBiTree(&((*T)->rchild)); } } //前序遍历 void preorderTraverse(BiNode *T) { if (T) { printf("%c", T->data); preorderTraverse(T->lchild); preorderTraverse(T->rchild); } } //中序遍历 void InorderTraverse(BiNode *T) { if (T) { InorderTraverse(T->lchild); printf("%c", T->data); InorderTraverse(T->rchild); } } //后序遍历 void postorderTraverse(BiNode *T) { if (T) { postorderTraverse(T->lchild); postorderTraverse(T->rchild); printf("%c", T->data); } } //求叶子节点 int LeafCount(BiNode *T) { static int count = 0; //注意此处的静态本地变量 if (T) { if (!(T->lchild) && !(T->rchild)) { printf("%c", T->data); count += 1; } LeafCount(T->lchild); LeafCount(T->rchild); } return count; } //求树高 int Hight(BiNode *T) { int hight = 0; int lh, rh; if (T) { lh = Hight(T->lchild); rh = Hight(T->rchild); hight = (lh > rh) ? lh : rh; return hight + 1; } else { return 0; } }
#include <stdio.h> #include <stdlib.h> #include "BiNode.h" #include "TreeOp.h" //测试函数 int main() { BiNode *t; createBiTree(&t); printf("前序遍历\n"); preorderTraverse(t); printf("\n"); printf("中序遍历\n"); InorderTraverse(t); printf("\n"); printf("后序遍历\n"); postorderTraverse(t); printf("\n"); printf("叶子节点数:%d\n", LeafCount(t)); printf("\n"); printf("树高:%d\n", Hight(t)); return 0; }