#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum dire {Left, Right} ;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{//二叉树节点声明
int Data;
BinTree Left;
BinTree Right;
};
BinTree CreateBTreeNode(int item){//创建新的节点
BinTree temp;
temp = (struct TNode*)malloc(sizeof(struct TNode));
if(! temp) return NULL;
temp -> Data = item;
temp -> Right = NULL;
temp -> Left = NULL;
return temp;
}
void Preorder(BinTree BT){//前序遍历树
if(!BT) return;
printf("%-4d", BT->Data);
if(BT->Left) Preorder(BT->Left);
if(BT->Right) Preorder(BT->Right);
}
void Postorder(BinTree BT){//后序遍历树
if(!BT) return;
if(BT->Left) Postorder(BT->Left);
if(BT->Right) Postorder(BT->Right);
printf("%-4d",BT->Data);
}
void inorder(BinTree BT){//中序遍历树
if(!BT) return;
if(BT->Left) inorder(BT->Left);
printf("%-4d",BT->Data );
if(BT->Right )inorder(BT->Right);
}
int print_at_level(BinTree BT, int level) {//层序遍历
if (BT == NULL|| level < 0)
return 0;
if (0 == level) {
printf(" %d", BT->Data );
return 1;
}
return print_at_level(BT->Left, level - 1) + print_at_level(BT->Right, level - 1);
}
void levelorder(BinTree BT) {//层序遍历树
int i = 0;
while(1) {
if (print_at_level(BT, i) == 0)
break;
i++;
}
}
int countLeaves(BinTree BT){//数树叶个数
if(!BT) return 0;
if(BT->Left == NULL && BT->Right == NULL) return 1;
//return countLeaves(BT->Left) + countLeaves( BT->Right);
//减少叶节点的递归
int left, right;
left = BT->Left ? countLeaves(BT->Left) : 0;
right = BT->Right ? countLeaves(BT->Right) : 0;
return left + right;
}
void Print(BinTree BT)//打印叶节点
{
if(BT)
{
if(!BT->Left && !BT->Right)
printf("%4d", BT->Data);
Print(BT->Left);
Print(BT->Right);
}
}
int CountLevel( BinTree BT ){//计算树的高度
if(!BT) return 0;
// int hLeft,hRight;
// hLeft= CountLevel(BT->Left);
// hRight = CountLevel(BT->Right);
// return (hLeft > hRight ? hLeft : hRight)+1;
return (CountLevel(BT->Left) > CountLevel(BT->Right) ? CountLevel(BT->Left) : CountLevel(BT->Right))+1;
}
int FindNode(BinTree BT , int item){
if(!BT) return 0;
if(BT->Data == item) return 1;
int temp = FindNode( BT->Left, item);
if(temp) return temp;
return FindNode(BT->Right,item);
}
BinTree FindNodeByPtr(BinTree BT , int item){
if(!BT) return NULL;
if(BT->Data == item) return BT;
BinTree temp = FindNodeByPtr(BT->Left, item);
if(temp) return temp;
return FindNodeByPtr(BT->Right, item);
}
int insert (BinTree BT, int parent, enum dire dir, int item){
BinTree temp = FindNodeByPtr( BT, parent);
if(!temp)return 0;
if(dir == Left){
if(temp -> Left) return 0;
temp -> Left = CreateBTreeNode(item);
}
else{
if(temp -> Right) return 0;
temp -> Right = CreateBTreeNode(item);
}
return 1;
}
OperationOnTree
最新推荐文章于 2021-09-04 21:39:19 发布