一些简单的关于二叉树的算法:
#include <iostream>
#include<cstdlib>
using namespace std;
typedef char ElemType;
const int MaxSize=100;
typedef struct node{
ElemType data;
struct node *lchild;
struct node *rchild;
}BTNode;
//创建二叉树
void CreateBTree(BTNode *&b,ElemType *str){
BTNode *St[MaxSize],*p;
b=NULL;
int top=-1,k;
ElemType ch;
for(int i=0;(ch=str[i])!='\0';i++){
switch(ch){
case '(':St[++top]=p;k=1;break;
case ')':top--;break;
case ',':k=2;break;
default:
p=(BTNode*)malloc(sizeof(BTNode));
p->data=ch;
p->lchild=p->rchild=NULL;
if(b==NULL)b=p;
else{
switch(k){
case 1:St[top]->lchild=p;break;
case 2:St[top]->rchild=p;break;
}
}
}
}
}
//计算二叉树的所有结点数
int Nodes(BTNode *b){
if(b==NULL)return 0;
else return Nodes(b->lchild)+Nodes(b->rchild)+1;
}
//输出二叉树的所有叶子结点
void DispLeaf(BTNode *b){
if(b!=NULL){
if(b->lchild==NULL&&b->rchild==NULL)cout<<b->data;
DispLeaf(b->lchild);
DispLeaf(b->rchild);
}
}
//求二叉树中结点值为x的结点的深度
int Level(BTNode* b,ElemType x,int h){
if(b==NULL) return 0;
else if(b->data==x) return h;
else{
int left=Level(b->lchild,x,h+1);
if(left!=0) return left;
else return Level(b->rchild,x,h+1);
}
}
//求二叉树中第k层的结点个数
void Lnodenum(BTNode* b,int h,int k,int &n){
if(b==NULL) return;
else{
if(h==k) n+=1;
else if(h<k){
Lnodenum(b->lchild,h+1,k,n);
Lnodenum(b->rchild,h+1,k,n);
}
}
}
//输出值为x的结点的所有祖先
bool ancestor(BTNode* b,ElemType x){
if(b==NULL) return false;
else {
if(b->data==x) return true;
else{
if(ancestor(b->lchild,x)||ancestor(b->rchild,x)){
cout<<b->data;
return true;
}
else return false;
}
}
}
int main() {
ElemType str[]="A(B(D(,G)),C(E,F))";
BTNode* b;
CreateBTree(b,str);
ElemType x;
cin>>x;
ancestor(b,x);
/* int k,n=0;
cin>>k;
Lnodenum(b,1,k,n);
cout<<n<<endl;
*/
// cout<<Nodes(b)<<endl;
// DispLeaf(b);
/* ElemType x;
cin>>x;
int h=Level(b,x,1);
if(h==0) cout<<"二叉树中没有节点值为"<<x<<"的结点。"<<endl;
else cout<<"二叉树中节点值为"<<x<<"的结点的深度为:"<<h<<endl;
*/
return 0;
}
不妥之处,请多多指教。