代码如下:
#include <stdio.h> #include <string.h> #include <stdlib.h> //二叉树的数据结构 typedef struct Tree { char data; struct Tree *lchild, *rchild; }Tree; //二叉树的创建 Tree* FrontCreateTree() { char c; Tree *T; scanf("%c",&c); if(' ' == c) T = NULL; else { T = (Tree *)malloc(sizeof(Tree)); T->lchild = FrontCreateTree(); T->data = c; T->rchild = FrontCreateTree(); } return T; } //前序遍历 void FrontShowTree(Tree *T) { if( T ) { printf("%c",T->data); FrontShowTree(T->lchild); FrontShowTree(T->rchild); } } //总节点计算 int count; void CountTreeNode(Tree *T) { if (tree) { count += 1; //计数 CountTreeNode(tree->lchild); CountTreeNode(tree->rchild); } } //树的高度计算 int DepTreeHeight(Tree *T) { int LeftTreeHight = 0, RightTreeHight = 0; if(T == NULL) return 0; else { LeftTreeHight = DepTreeHeight(T->lchild); RightTreeHight = DepTreeHeight(T->rchild); if( LeftTreeHight > RightTreeHight ) return LeftTreeHight + 1; else return RightTreeHight + 1; } } //每层节点计算 void CountStateNode(Tree *T, int level, int *levelbuf) { if( T ) { levelbuf[level]++; CountStateNode(T->lchild,level + 1,levelbuf); CountStateNode(T->rchild,level + 1,levelbuf); } } //复制二叉树 Tree *CopyBinaryTree(Tree *T) { if(T) { Tree *NewTree = (Tree* )malloc(sizeof(Tree)); NewTree->data = T->data; NewTree->lchild = CopyBinaryTree(T->lchild); NewTree->rchild = CopyBinaryTree(T->rchild); return NewTree; } else return NULL; }
简单测试:
int main() { int state,i; int NodeBuf[100] = {0}; Tree* T = FrontCreateTree(); FrontShowTree(T); CountTreeNode(T); printf("count = %d\n",count); state = DepTreeHeight(T); printf("state = %d\n",state); CountStateNode(T,1,NodeBuf); for(i = 1; i <= state; i++) printf("%d-",NodeBuf[i]); Tree* NewT = CopyBinaryTree(T); FrontShowTree(T); return 0; }
输入如下二叉树数据结构:ABDH I E CFJ K G
(注意输入空格)
结果如下所示: