前端算法系列-二叉树03

73 阅读1分钟

110. 平衡二叉树

var fn = (root) => {
    if(!root) return 0
    let lH = fn(root.left)
    let rH = fn(root.right)
    if(lH === -1 || rH === -1) return -1
    return Math.abs(lH-rH) > 1 ? -1 : 1 + Math.max(lH,rH)
}

var isBalanced = function(root) {
    if(!root) return true
    return fn(root) === -1 ? false : true
};

257. 二叉树的所有路径

var binaryTreePaths = function(root) {
    let res = []
    let path = (root,prefix) => {
        if(!root) return null
        if(root && !root.left && !root.right) res.push(prefix ? `${prefix}->${root.val}` :`${root.val}` )
        path(root.left,prefix ? `${prefix}->${root.val}` :`${root.val}` )
        path(root.right,prefix ? `${prefix}->${root.val}` :`${root.val}`)
        return 
    }
    path(root,"")
    return res
};

404. 左叶子之和

var sumOfLeftLeaves = function(root,isLeft = false) {
    if(!root) return 0
    if(isLeft && !root.left && !root.right){
        return root.val +  sumOfLeftLeaves(root.left,true) + sumOfLeftLeaves(root.right)
    }
    return sumOfLeftLeaves(root.left,true) + sumOfLeftLeaves(root.right)
};

222. 完全二叉树的节点个数

完全二叉树只有两种情况,情况一:就是满二叉树,情况二:最后一层叶子节点没有满。

对于情况一,可以直接用 2^树深度 - 1 来计算,注意这里根节点深度为1。

对于情况二,分别递归左孩子,和右孩子,递归到某一深度一定会有左孩子或者右孩子为满二叉树,然后依然可以按照情况1来计算。


var countNodes = function(root) {
    //利用完全二叉树的特点
    if(root === null) {
        return 0;
    }
    let left = root.left;
    let right = root.right;
    let leftDepth = 0, rightDepth = 0;
    while(left) {
        left = left.left;
        leftDepth++;
    }
    while(right) {
        right = right.right;
        rightDepth++;
    }
    if(leftDepth == rightDepth) {
        return Math.pow(2, leftDepth+1) - 1;
    }
    return countNodes(root.left) + countNodes(root.right) + 1;
};