结构体定义
#include <stdio.h>
#include <stdlib.h>typedef struct node
{
char data;
struct node *lChild, *rChild;
} tNode,*tPointer;
递归先序创建二叉树
tPointer createTree(tPointer t)
{
char c;
scanf("%c",&c);if(c == '#')
{
t = NULL;
}
else
{
t = (tPointer)malloc(sizeof(tNode));
t -> data = c;
t -> lChild = NULL;
t -> rChild = NULL;t -> lChild = createTree(t -> lChild);//建立左子树
t -> rChild = createTree(t -> rChild);//建立右子树
}
return t;
}
递归探索二叉树
//递归先序遍历二叉树读取depth
int getDepth(tPointer t)
{
int depth,lDepth,rDepth;
depth = lDepth = rDepth = 0;if(t)depth++;
if(t -> lChild)
{
lDepth = getDepth(t -> lChild);
}
else
{
lDepth = 0;
}if(t -> rChild)
{
rDepth = getDepth(t -> rChild);
}
else
{
rDepth = 0;
}if(lDepth >= rDepth)
{
depth += lDepth;
}
else
{
depth += rDepth;
}return depth;
}//递归先序遍历二叉树读取sumNode
int getSumNode(tPointer t)
{
int sumNode = 0;if(t)sumNode++;
if(t -> lChild)sumNode += getSumNode(t -> lChild);
if(t -> rChild)sumNode += getSumNode(t -> rChild);return sumNode;
}//递归先序遍历二叉树读取oneNode
int getOneNode(tPointer t)
{
int oneNode = 0;if(t && !(t -> lChild) &&!(t -> rChild))oneNode++;
if(t -> lChild)oneNode += getOneNode(t -> lChild);
if(t -> rChild)oneNode += getOneNode(t -> rChild);return oneNode;
}
递归删除二叉树
void destroyTree(tPointer t)
{
if(t)
{
if(t -> lChild)destroyTree(t -> lChild);//删除左子树
if(t -> rChild)destroyTree(t -> rChild);//删除右子树
free(t);
t = NULL;
}
}
主函数
int main()
{
tPointer t = createTree(t);printf("%d\n",getDepth(t));
printf("%d\n",getSumNode(t));
printf("%d\n",getOneNode(t));
destroyTree(t);
return 0;
}