二叉树的最小高度,最大高度(深度)和宽度

最大高度

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;
}

 

posted @ 2017-05-13 17:36  全玉  阅读(5116)  评论(0编辑  收藏  举报