zoukankan      html  css  js  c++  java
  • 二叉树最大距离(直径)

    方法一 计算每个节点的左子树和右子树的高度和,加上根本身(边数为2),取最大值

    二叉树的最大距离,一定是经过根或者某个子树的根的路径,其两个端点必然是叶子节点或者根节点。计算二叉树的高度,并且比较经过该节点的最大距离,取

    最大者。其中,getTreeDistance的起点是-1,其值为二叉树的高度减1,即高度路径上的点之间的边的条数,即距离。getTreeDistance引入了新的概念描述,

    getTreeHeight是求树的高度,但是其计算时候要减去1.经过一个根节点的最大距离,就是其左子树最大高度距离(不是最大距离),加上其右子树最大高度距离,加上

    左右到根节点的距离,即2,然后与一个外部变量比较,因此使用了两个函数。

    实现代码如下:

    function Node(val){
        this.val = val;
        this.left = null;
        this.right = null;
    }
    function getMaxDistance(){ var max_d = 0; getTreeHeight(root);//或者getTreeDistance(root); return max_d; }
    function getTreeDistance(root){ if(!root){ return -1; } var lh = getTreeDistance(root.left), rh = getTreeDistance(root.right); var distance = lh + rh + 2; max_d = Math.max(distance,max_d); return Math.max(lh,rh) + 1; }
    function getTreeHeight(root){ if(!root){ return 0; } var lh = getTreeHeight(root.left), rh = getTreeHeight(root.right); var distance = (lh -1) + (rh - 1) + 2; max_d = Math.max(distance,max_d); return Math.max(lh,rh) + 1; }
    方法二 按照节点是否跨根,分为左子树最大距离,右子树最大距离,左右子树最大深度加到根节点的距离,即2,取最大者
    同样区分高度距离和高度,起点不同,高度距离为-1,高度为0,用对象距离结果,然后返回。
    function getMaxDistance(root){
        if(!root){
            return {
                maxDist:-1,                    
                maxDistance:0
            }
        }
        var lRes = getMaxDistance(root.left),
            rRes = getMaxDistance(root.right);
        var result = {
            maxDist:Math.max(lRes.maxDist,rRes.maxDist) + 1,
            maxDistance:Math.max(lRes.maxDistance,rRes.maxDistance,lRes.maxDist + rRes.maxDist + 2)
        }
        return result;
    }
    
    function getMaxDistance(root){
        if(!root){
            return {
                maxDepth:0,                    
                maxDistance:0
            }
        }
        var lRes = getMaxDistance(root.left),
            rRes = getMaxDistance(root.right);
        var result = {
            maxDepth:Math.max(lRes.maxDepth,rRes.maxDepth) + 1,
            maxDistance:Math.max(lRes.maxDistance,rRes.maxDistance,(lRes.maxDepth-1) + (rRes.maxDepth-1) + 2)
        }
        return result;
    }

    出处: http://blog.csdn.net/flyinghearts/article/details/5605995

        http://www.cnblogs.com/miloyip/archive/2010/02/25/1673114.html    

  • 相关阅读:
    Java操作excel,读取及导出
    vue 在package.json配置对外暴露访问地址(手机端访问本地项目地址)
    element UI upload组件上传附件格式限制
    linux之vim/vi快速复制多行内容的快捷键
    使用vant的Toast组件时提示not defined
    如何使用js判断当前页面是pc还是移动端打开的
    JavaScript 保留两位小数函数
    Linux其他命令
    linux学习ls的三个选项 lha的作用和隐藏文件的知识
    vue+ element-ui el-table组件自定义合计(summary-method)坑
  • 原文地址:https://www.cnblogs.com/mengff/p/6870011.html
Copyright © 2011-2022 走看看