day48 计算机考研408真题2014年41题(Java)

296 阅读2分钟

题目来源: 计算机考研408真题2014年41题

题目描述:

  • 描述: 41.(13分)二叉树的带权路径长度(WPL)是二叉柯中所有叶结点的带权路径长度之和。给定 一棵二叉树T.采用二又链表存储,结点结构如下: image.png 其中叶结点的weight域保存该结点的非负权值。设root为指向T的根结点的指针,请设计求T的WPL的算法。 要求:
    1)给出算法的基本设计思想。
    2)根据设计思想,采用C、C++或Java语言描述算法,关键之处给出注释.
    3)说明你所设计算法的时间复杂度和空间复杂度。

思路:先序递归遍历

  • 把每个结点的深度作为递归函数的一个参数传递
    • 1.若该结点是叶子结点,则变量wpl加上该结点的深度与权值之积,深度参数均为本结点的深度参数加1
    • 2.若该结点非叶子结点,若左子树不为空,对左子树调用递归算法,计算出左子树的的lwpl
    • 3.若该结点非叶子结点,若右子树不为空,对右子树调用递归算法,计算出右子树的的rwpl
    • 4.最后返回计算出的(lwpl+rwpl)即可

具体实现:

class BiTree{
    int weight;            //权值
    BiTree lchild,rchild;  //左右孩子结点

    BiTree(int weight){
        this.weight = weight;
        this.lchild = null;
        this.rchild = null;
    }

    int wpl_PreOrder(BiTree root,int deep){  //求WPL的方法
        int lwpl = 0, rwpl = 0;
        if(root.lchild==null&&root.rchild==null){
            return deep*root.weight;
        }
        if(root.lchild!=null){
            lwpl = wpl_PreOrder(root.lchild,deep+1);
        }
        if(root.rchild!=null){
            rwpl = wpl_PreOrder(root.rchild,deep+1);
        }
        return lwpl+rwpl;
    }
}

public class day408_14 {  //测试
    public static void main(String[] args) {
        BiTree biTree = new BiTree(2);   //假设了三个结点
        biTree.lchild = new BiTree(3);
        biTree.rchild = new BiTree(4);
        System.out.println(biTree.wpl_PreOrder(biTree,0));   //结果为7(2*0+3*1+4*1)
    }
}

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 22 天,点击查看活动详情