2014年408真题----二叉树求带权路径值

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>

typedef int BiElemType;
typedef struct BiTNode {
    BiElemType data;
    struct BiTNode *lChild;
    struct BiTNode *rChild;//左右节点
} BiTNode, *BiTree;
//辅助队列
typedef struct tag {
    BiTree p;//树的某一个节点,指针类型,保存申请节点的指针
    struct tag *pnext;
} tag_t, *ptag_t;

//前序遍历,深度优先遍历
int wpl = 0;

void preOrder(BiTree p, int deep) {
    if (p) {
//        printf("%c", p->data);
        if (p->lChild == NULL && p->rChild == NULL) {//叶子节点
            wpl += (p->data) * deep;
        }
        deep++;
        preOrder(p->lChild, deep);
        //递归
        preOrder(p->rChild, deep);
    }
}

void inOrder(BiTree p) {
    if (p) {
        inOrder(p->lChild);
        printf("%c", p->data);
        //递归
        inOrder(p->rChild);
    }
}

void postOrder(BiTree p) {
    if (p) {
        postOrder(p->lChild);
        postOrder(p->rChild);
        printf("%c", p->data);
        //递归
    }
}

int WPL(BiTree tree) {
    preOrder(tree, 0);
    return wpl;
}

int main() {
    BiTree p;//指向新申请的树节点
    BiTree tree = NULL;//初始化根节点
    //队头,队尾,新节点,新节点父元素
    ptag_t phead = NULL, ptail = NULL, listpnew = NULL, pucr = NULL;
    char c;
    while (scanf("%c", &c)) {
        if (c == '\n') {
            break;;
        }
        p = (BiTree) calloc(1, sizeof(BiTNode));
        p->data = c;
        listpnew = (ptag_t) calloc(1, sizeof(tag_t));//给队列节点申请空间
        listpnew->p = p;
        if (tree == NULL) {
            tree = p;
            //第一个节点既是队列头也是队列尾
            phead = listpnew;
            ptail = listpnew;
            pucr = listpnew;
        } else {
            ptail->pnext = listpnew;
            ptail = listpnew;
            //将数放入左孩子
            if (pucr->p->lChild == NULL) {
                pucr->p->lChild = p;
            } else if (pucr->p->rChild == NULL) {
                pucr->p->rChild = p;
                pucr = pucr->pnext;
            }
        }
    }
    printf("%d",WPL(tree));
//    preOrder(tree);
//    inOrder(tree);
//    postOrder(tree);
    return 0;
}
相关推荐
阿史大杯茶35 分钟前
Codeforces Round 976 (Div. 2 ABCDE题)视频讲解
数据结构·c++·算法
不穿格子衬衫2 小时前
常用排序算法(下)
c语言·开发语言·数据结构·算法·排序算法·八大排序
aqua35357423582 小时前
蓝桥杯-财务管理
java·c语言·数据结构·算法
韬. .3 小时前
树和二叉树知识点大全及相关题目练习【数据结构】
数据结构·学习·算法
野草y3 小时前
数据结构(7.4_1)——B树
数据结构·b树
Word码3 小时前
数据结构:栈和队列
c语言·开发语言·数据结构·经验分享·笔记·算法
代码雕刻家3 小时前
数据结构-3.10.队列的应用
服务器·数据结构
五花肉村长3 小时前
数据结构-队列
c语言·开发语言·数据结构·算法·visualstudio·编辑器
秋落风声3 小时前
【数据结构】---图
java·数据结构··graph
CyberMuse3 小时前
AVL平衡树(AVL Tree)
数据结构