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;
}
相关推荐
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后1232 天前
【数据结构】二叉树的概念
数据结构·二叉树
散1122 天前
01数据结构-01背包问题
数据结构
消失的旧时光-19432 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww2 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚3 天前
[数据结构] 排序
数据结构
睡不醒的kun3 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌3 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long3 天前
【数据结构】深入理解堆:概念、应用与实现
数据结构
IAtlantiscsdn3 天前
Redis7底层数据结构解析
前端·数据结构·bootstrap