zoukankan      html  css  js  c++  java
  • 二叉树的最小高度,最大高度(深度)和宽度

    最大高度

    function getMaxHeight(root){
        if(root == null) return 0;
    
        return 1 + Math.max(getMaxHeight(root.left),getMaxHeight(root.right));
    }

    最小高度

    function getMinHeigth(root){
        if(!root) return 0;
        return 1 + Math.min(getMinHeight(root.left),getMinHeight(root.right));
    }

    二叉树宽度

    递归方法

    function getMaxWidth(root){
        if(root == null) return 0;
        if(root.left == null && root.right == null) return 1;
    
        return getMaxWidth(root.left) + getMaxWdith(root.right);
    }

    非递归方法求二叉树的高度和宽度

    //使用层次遍历,求最大高度和最大宽度
    function getMaxSize(root){
        let queue = [root];
        let width = 0;
        let height = 0;
        while(queue.length){
            let levelSize = queue.length;
            width = Math.max(levelSize,width);
            height++;
    
            while(levelSize--){
                let node = queue.shift();
                if(node.left) queue.push(node.left);
                if(node.right) queue.push(node.right);
            }
        }
    
        return [width,height];
    }

    还有一种在每行末尾添加null的方式,虽然不及上面的简洁,但是思路值得肯定

    function bfs(root){
        if(!root) return;
    
        //第一行先在末尾加个null
        let queue = [root,null];
        let deep = 0;
    
        //rows可以记录每行的宽度
        let rows = [];
    
        while(queue.length){
            let node = queue.shift();
            //为null表示本行结束
            if(node == null){
                deep++;
    
                //本行结束,下一行的node已经push完毕,在此处加null,就是在下一行的末尾加null
                //queue的长度若为0,则说明最后一行,无需再加null
                if(queue.length) queue.push(null);
            }
            else{
                rows[deep] = ~~rows[deep] + 1;
                if(node.left) queue.push(node.left);
                if(node.right) queue.push(node.right);
            }
        }
        return deep;
    }
  • 相关阅读:
    JAVA中变量的初始化
    取得301转向后的地址
    history for html5
    php traits 介绍
    android 笔记
    C posix 笔记
    笔记
    C 常用库
    cocos2dx:利用CCSpriteBatchNode优化渲染效率
    C实现将指定秒数转化为时:分:秒格式
  • 原文地址:https://www.cnblogs.com/mengff/p/6849701.html
Copyright © 2011-2022 走看看