王道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