版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jeffscott/article/details/70187151
一、题目描述
二、算法思想:
本算法目的是求带权路径的长度,就是叶子节点的深度乘以叶子的权重之和。关键是如何求出每个叶子节点的深度,在这里最简单的方法就是利用递归算法。
三、核心代码:
int WPL(BiTNode*root)//封装先序法
{
return wp1_PreOrder(root,0);
}
int wp1_PreOrder(BiTNode*root,int deep)
{
static int wp1=0;//定义局部静态变量用来存储路径长度
if(root->lchild==NULL&&root->rchild==NULL)//如果左右孩子节点都为空,证明为叶子节点
wp1+=deep*root->weight;//将加权路径增加
if(root->lchild!=NULL)//左孩子不为空,递归遍历左孩子
wp1_PreOrder(root->lchild,deep+1);
if(root->rchild!=NULL)//右孩子不为空,递归遍历右孩子
wp1_PreOrder(root->rchild,deep+1);
return wp1;
}
四、完整代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct BiTNode{ //定义结构体
int weight; //节点数据
struct BiTNode *lchild,*rchild;//左右孩子指针
}BiTNode,*BiTree;
int wp1_PreOrder(BiTNode*root,int deep);//先序遍历
int WPL(BiTNode*root);//求
BiTree DLR_creat() ; //先序创建二叉树
void PreOrderTraverse(BiTree T);//先序遍历
int main()
{
BiTNode* root=NULL;
printf("请按先序遍历依次输入,以-1表示指针域为空:\n");//由于算法的递归出口是返回NULL,
root=DLR_creat(); //所以在进行输入时,必须首先将二叉树变成拓展二叉树
printf("先序遍历:");
PreOrderTraverse(root); //前序遍历
printf("\nthe WPL is:% d\n",WPL(root));// 打印结果
return 0;
}
int WPL(BiTNode*root)//封装先序法
{
return wp1_PreOrder(root,0);
}
int wp1_PreOrder(BiTNode*root,int deep)
{
static int wp1=0;//定义局部静态变量用来存储路径长度
if(root->lchild==NULL&&root->rchild==NULL)//如果左右孩子节点都为空,证明为叶子节点
wp1+=deep*root->weight;//将加权路径增加
if(root->lchild!=NULL)//左孩子不为空,递归遍历左孩子
wp1_PreOrder(root->lchild,deep+1);
if(root->rchild!=NULL)//右孩子不为空,递归遍历右孩子
wp1_PreOrder(root->rchild,deep+1);
return wp1;
}
BiTree DLR_creat() //先序创建二叉树
{
int weight;
BiTree root;
scanf("%d", &weight);
if (weight == -1)
return NULL;
else
{
root = (BiTree)malloc(sizeof(BiTNode)* 1);//申请动态内存
if (root == NULL)//异常情况处理
{
printf("创建失败!\n");
exit(EXIT_FAILURE);
}
root->weight = weight;
root->lchild=DLR_creat();
root->rchild = DLR_creat();
}
return root;
}
//先序遍历二叉树
void PreOrderTraverse(BiTree T){
if(T){
printf("%-3d",T->weight);
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}
}
五、测试分析: