数据结构中,二叉树用到的算法代码综合

#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;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值