准备:
#include<iostream>
using namespace std;
typedef char ElemType;
#define END '#'
typedef struct BtNode
{
BtNode *leftchild;
BtNode *rightchild;
ElemType data;
}BtNode,*BinaryTree;
//购买结点
BtNode *Buynode()
{
BtNode *p=(BtNode *)malloc(sizeof(BtNode));
if(NULL==p) exit(1);
memset(p,0,sizeof(BtNode));
return p;
}
void *Freenode(BtNode *ptr)
{
free(ptr);
}
1.在二叉树中查找值X
//在二叉树中查找值x
BtNode * FindValue(BtNode *ptr,ElemType x)
{
ptr=root;
if(ptr==NULL ||ptr==x)
{
return ptr;
}
else
{
BtNode *p=FindValue(ptr->leftchild ,x);
if(p==NULL)
{
p=FindValue(ptr->rightchild ,x);
}
return p;
}
}
2.知道孩子结点,找到母亲结点
//知道孩子结点,找到母亲结点
BtNode * Parent(BtNode *ptr,BtNode *child)
{
if(ptr==NULLL||ptr->leftchild ==NULL||ptr->rightchild ==NULL)
{
return ptr;
}
else
{
BtNode *p=Parent(p->leftchild ,child);
if(p==NULL)
{
p=Parent(p->rightchild ,child);
}
return ptr;
}
}
BtNode *FindParent(char *ptr,char *child)
{
if(ptr==NULL||ptr==child||child==NULL)
{
return NULL;
}
else
{
return Parent(ptr,child);
}
}
3.求二叉树的大小
//求二叉树的大小
int Size(BtNode *ptr)
{
if(ptr==NULL)
{
return 0;
}
else
{
return Size(ptr->leftchild )+Size(ptr->rightchild )+1;
}
}
4.求二叉树的深度
//求二叉树的深度
int Max(int x,int y)
{
return x>y? x:y ;
}
int Depth(BtNode *ptr)
{
if(ptr==NULL)
{
return 0;
}
else
{
return Max(Depth(ptr->leftchild ),Depth(ptr->rightchild ))+1;
}
}
5.求叶子结点的个数
//求叶子结点的个数
int SizeLeaf(BtNode *ptr)
{
if(ptr==NULL)
{
return 0;
}
else if(ptr->leftchild ==NULL && ptr->rightchild ==NULL)
{
return 1;
}
else
{
return SizeLeaf(ptr->leftchild )+SizeLeaf(ptr->rightchild );
}
}