#include <iostream>
#include <vector>
using namespace std;
struct BTNode
{
char data;
BTNode* lchild;
BTNode* rchild;
};//定义节点结构
void CreateBTnode(BTNode* &p)
{
//cout<<"please input your node "<<endl;
char ch;
cin>>ch;
if(ch!='#')
{
p=(BTNode*)malloc(sizeof(BTNode));
p->data=ch;
p->lchild=p->rchild=NULL;
CreateBTnode(p->lchild);
CreateBTnode(p->rchild);
}
}//创建二叉树
BTNode* FindBT(BTNode* &p,char k)
{
BTNode* q;
if(p==NULL) return NULL;
else if(p->data==k) return p;
else
{
q=FindBT(p->lchild,k);
if(q==NULL)
q=FindBT(p->rchild,k);
return q;
}
} //查找二叉树中值为x的节点
int Height(BTNode* p)
{
int h1,h2,h;
if(p==NULL) return 0;
else
{
h1=Height(p->lchild);
h2=Height(p->rchild);
h=h1>h2?h1:h2;
return (h+1);
}
}//查询二叉树的高度
void LeafPrint(BTNode* p)
{
if(p==NULL) return ;
else
{
if(p->lchild==NULL&&p->rchild==NULL)
cout<<p->data<<endl;
else
{
LeafPrint(p->lchild);
LeafPrint(p->rchild);
}
}
}//输出二叉树的所有叶子节点
int Level(BTNode* p,char x,int k)
{
if(p!=NULL)
{
int q;
if(p->data==x) return k;
else
{
q=Level(p->lchild,x,k+1);
if(q==0)
q=Level(p->rchild,x,k+1);
return q;
}
}
else return 0;
}//查找字符x所在节点的层次
vector<BTNode*> fa;
int ancestor(BTNode* p,char x)
{
if(p==NULL) return 0;
if(p->data==x) return 1;
if(ancestor(p->lchild,x)||ancestor(p->rchild,x))
{
cout<<p->data<<endl;
fa.push_back(p);
return 1;
}
}//输出和存储节点值为x的所有祖先节点
void PrintBT(BTNode* p)
{
if(p==NULL) return;
else
{
cout<<p->data<<endl;
PrintBT(p->lchild);
PrintBT(p->rchild);
}
}//打印树的所有节点值
int main()
{
BTNode* p,*q,*p1;
CreateBTnode(p);
PrintBT(p);
q=FindBT(p,'c');
cout<<Height(p)<<endl;
LeafPrint(p);
cout<<Level(p,'d',1);
fa.clear();
ancestor(p,'g');
printf("wo de\n");
for(int i=0;i<fa.size();i++)
{
if(fa[i]!=NULL) cout<<fa[i]->data<<endl;
}
}
数据结构中,二叉树用到的算法代码综合
最新推荐文章于 2024-08-09 20:13:32 发布