【数据结构】(二叉树)求二叉树带权路径长度(WPL)递归&&非递归

求二叉树带权路径长度(WPL)

简介:*树的带权路径长度(Weighted Path Length of Tree,简记为WPL)*二叉树的带权路径长度是每个叶子节点深度(高度)与其指定权重的乘积总和


算法思想:对于求带权路径长度我们只需要找到叶子结点以及叶子结点所在的层数即可,本文将采取递归与非递归两种思路来解题

typedef struct BiNode{
	int weight; //权值
	BiNode *lchild,*rchild;
};

递归求解:

int wpl=0;
int wpl_preorder(BiNode *Root,int level){
	int wpl_=0;
	if(!Root)
		return 0;
	if(Root->rchild==NULL&&Root->lchild==NULL){
		 wpl_=Root->weight*level;
	}
	wpl+=wpl_preorder(Root->lchild,level+1);
	wpl+=wpl_preorder(Root->rchild,level+1);
	return wpl_;
}

非递归求解(使用层次遍历):

这里的代码引用了求二叉树的高度或者求二叉树宽度的代码若有不懂请看我之前博文 传送门求二叉树高度 传送门求二叉树宽度

int wpl_levelorder(BiNode *Root){
	if(!Root)
		return 0;
	BiNode *que[MaxSize];
	int front=-1,rear=-1;
	int counter=0;
	int size=0;
	int level=0;
	int wpl=0;
	que[++rear]=Root;
	counter++;
	while(front<rear){
		level++;
		size=counter;
		counter=0;
		while(size--){
			
			Root=que[++front];
			if(Root->lchild==NULL&&Root->rchild==NULL){
				wpl+=Root->weight*level;	
			}
			if(Root->rchild!=NULL){
				que[++rear]=Root->rchild;
				counter++;
			}
			if(Root->lchild!=NULL){
				que[++rear]=Root->lchild;
				counter++;
			}	
		}
	}
	return wpl;

}

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值