树的题目(三)

//求最近公共祖先
BiTree CommonAncestor(BiTree T,BiTree p,BiTree q){
	if(!T||T==p||T==q)return T;//先把p,q结点指针返回 
	BiTree left=CommonAncestor(T->lchild,p,q);
	BiTree right=CommonAncestor(T->rchild,p,q);
	if(!left && !right)return NULL;//一直返回p,q结点指针
	else if(left && !right)return left;
	else if(!left && right)return right;
	else return T;//直至找到公共祖先结点,一直返回公共祖先结点指针 
}
//另外的方法是根据后序遍历访问到某个结点时,
//栈内元素都是该结点的祖先结点这一特性
//可以得到在两个栈中的p,q结点的全部祖先
//然后拿一个p的祖先与q的祖先依次比较,若没有相同结点 
//再拿下一个p的祖先与q的祖先依次比较
//也就是双重for循环比较 
 
//打印根结点到每个叶结点的路径
void Route(BiTree T,char* path,int pathlen){
	if(!T)return;
	if(T->lchild==NULL&&T->rchild==NULL){
		printf("%c: ",T->data);
		for(int i=pathlen-1;i>=0;i--)
			printf("%c ",path[i]);
		printf("\n");
	}
	path[pathlen++]=T->data;
	Route(T->lchild,path,pathlen);
	Route(T->rchild,path,pathlen);	
} 


//求二叉树的宽度
int maxw=1,lastn=1,currentn=0;
void Width(BiTree T){
	InitQueue(Q);
	EnQueue(Q,T);
	BiTree p;
	while(!IsEmpty(Q)){
		while(lastn>0){
			DeQueue(Q,p);
			if(p->lchild!=NULL){
				EnQueue(Q,p->lchild);
				currentn++;
			}
			if(p->rchild!=NULL){
				EnQueue(Q,p->rchild);
				currentn++;
			}
			lastn--;
		}
		maxw=currentn>maxw?maxw:currentn;
		lastn=currentn;
		currentn=0;
	} 
}


void BiTree2Exp(BiTree root,int d){
	if(!root)return;
	if(root->lchild==NULL&&root->rchild==NULL){
		printf("%s",root->data);
	} 
	if(d>1)printf("(");
	BiTree2Exp(root->lchild);
	printf("%s",root->data);
	BiTree2Exp(root->rchild);
	if(d>1)printf(")");
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值