二叉树,经典数据结构,应用广泛
一般来讲二叉树的重点在于遍历,因为几乎所有关于二叉树的操作都可以通过遍历解决,同时二叉树的遍历(先根,中根,后根)也有比较强的应用性(比如数学表达式求值)
下面给出常规的递归做法,递归好处很明显,代码简单易懂,代码里面的求树的深度,节点数,叶子节点数,也都用的是递归的方法
/**********************************************
二叉树常用操作:
遍历(前中后,以及逐层遍历)
遍历是二叉树到重点,其他到操作都可以通过遍历完成
**********************************************/
#include<stdio.h>
#include<malloc.h>
struct BTreeNode
{
char data;
struct BTreeNode * left;
struct BTreeNode * right;
};
typedef struct BTreeNode BTNode,* BTree;
/***************************************
相当于 定义了(struct BTreeNode)的同义词 BTNode;
以及(struct BTreeNode *)的同义词 BTree(这里typedef起到了隐藏指针操作的作用)
该结构体声明也可以这么写:
typedef struct BTreeNode
{
char data;
struct BTreeNode * left;
struct BTreeNode * right;
}BTNode,*BTree;
****************************************/
//初始化二叉树
void InitBTree(BTree *bTree){
*bTree = NULL;
return ;
}
//构造二叉树
void CreateBTree(BTree &root){
char data;
data = getchar();
if(data=='0'){
root = NULL;
}
else {
root = (BTree)malloc(sizeof(BTNode));
root->data = data;
CreateBTree(root->left);
CreateBTree(root->right);
}
}
//判断二叉树是否为空
int EmptyBTree(BTree bTree){
if(bTree == NULL) return 1;
return 0;
}
//二叉树深度
int BTreeDepth(BTree bTree){
if(bTree == NULL){
return 0;
}
else {
int leftDepth = BTreeDepth(bTree->left);
int rightDepth = BTreeDepth(bTree->right);
if(leftDepth > rightDepth)
return leftDepth+1;
else
return rightDepth+1;
}
}
//二叉树节点数
int BTreeNode(BTree bTree){
if(bTree == NULL)return 0;
else return BTreeNode(bTree->left)+BTreeNode(bTree->right)+1;
}
//二叉树叶子节点数
int BTreeLeafNode(BTree bTree){
if(bTree == NULL)return 0;
else if(bTree->left==NULL && bTree->right==NULL)return 1;
else return BTreeLeafNode(bTree->left)+BTreeLeafNode(bTree->right);
}
//先根遍历
void PreOrder(BTree bTree)//void PreOrder(struct BTreeNode* *bTree)
{
if(bTree != NULL){
printf("%c ",bTree->data);
PreOrder(bTree->left);
PreOrder(bTree->right);
}return ;
}
//中根遍历
void InOrder(BTree bTree){
if(bTree != NULL){
InOrder(bTree->left);
printf("%c ",bTree->data);
InOrder(bTree->right);
}return ;
}
//后根遍历
void PostOrder(BTree bTree){
if(bTree != NULL){
PostOrder(bTree->left);
PostOrder(bTree->right);
printf("%c ",bTree->data);
}return ;
}
int main()
{
BTree bTree;
InitBTree(&bTree);
//puts("Input:ABD000CE00F00");
puts("Input:12300400500");
/*********************
1
/ \
2 5
/ \
3 4
*********************/
CreateBTree(bTree);
int nodes = BTreeNode(bTree);
printf("二叉树节点数:%d\n",nodes);
int leafNodes = BTreeLeafNode(bTree);
printf("二叉树叶子节点数:%d\n",leafNodes);
puts("");
puts("先根遍历:");
PreOrder(bTree);puts("");
puts("");
puts("中根遍历:");
InOrder(bTree);puts("");
puts("");
puts("后根遍历:");
PostOrder(bTree);puts("");
puts("");
return 0;
}