本文主要是介绍王道c语言-求二叉树的带权路径长度WPL,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#include <stdio.h>
#include <stdlib.h>typedef int BiElemType;
typedef struct BiNode {BiElemType weight;struct BiNode *left; //写成lchild rchild也可以,但left比较符合题意更准确struct BiNode *right;
} BiNode, *BiTree;typedef struct tag {BiTree p;//树的某个结点的地址值struct tag *pnext;
} tag, *ptag;//int wpl=0;//等价于static int wpl = 0; 全局变量 vs 静态变量int PreOrder(BiTree p,int deep) {static int wpl=0;//只会初始化一次if(p){
// printf("%c--%d\t",p->weight,deep);if(p->left==NULL&&p->right==NULL){wpl+= p->weight*deep;}PreOrder(p->left,deep+1);PreOrder(p->right,deep+1);}return wpl;
}int main() {BiTree pnew;BiTree tree = NULL;//phead= ptail= pcur=listpnew=NULL;是错误的,每个指针需要单独声明和初始化,// 可以先声明,后一起初始化 phead= ptail= pcur=listpnew=NULL;ptag phead=NULL, ptail=NULL, pcur=NULL,listpnew=NULL;char c;while(scanf("%c",&c)) {if(c=='\n'){break;}pnew = (BiTree) calloc(1, sizeof(BiNode));pnew->weight = c;listpnew = (ptag) calloc(1, sizeof(tag));listpnew->p = pnew;if (tree == NULL) {tree = pnew;phead = listpnew;ptail = listpnew;pcur = listpnew;} else {ptail->pnext = listpnew;ptail = ptail->pnext;if (pcur->p->left == NULL) {pcur->p->left = pnew;} else if (pcur->p->right == NULL) {pcur->p->right = pnew;pcur = pcur->pnext;}}}printf("wpl= %d ",PreOrder(tree,0));return 0;
}
输入:1234567
输出:wpl= 428
这篇关于王道c语言-求二叉树的带权路径长度WPL的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!