110.222. 平衡二叉树/完全二叉树的节点个数

110 222

// 升级一下initTree的代码
const initTree = (inputList) => {
    const total = inputList.length;
    if(!inputList[0])return null;
    inputList[0] = new TreeNode(inputList[0]);
    inputList.forEach((el,index) => {
        let leftP = null;
        let rightP = null;
        if (el === null) return;
        if (index*2+1 < total) {
            leftP = inputList[index*2+1] !== null ? new TreeNode(inputList[index*2+1]): null;
            inputList[index*2+1] = leftP;
        } 
        if (index*2+2 < total) {
            rightP = inputList[index*2+2] !== null ? new TreeNode(inputList[index*2+2]): null;
            inputList[index*2+2] = rightP;
        }
        inputList[index].left = leftP;
        inputList[index].right = rightP;
    });
    return inputList[0];
}

function TreeNode(val, left, right) {
    this.val = (val===undefined ? 0 : val)
    this.left = (left===undefined ? null : left)
    this.right = (right===undefined ? null : right)
}

const cntHeight = (root) => {
    if (!root) return 0;
    const queue = [root];
    let treeHeight = 0;
    while(queue.length) {
        const qLen = queue.length;
        for(let i=0; i<qLen; i++) {
        // for(let i=0; i< queue.length; i++) {
        // 注意,此处qlen如果直接写成queue.length似乎会得到一些奇怪的结果,leetcode会不通过
            const curNode = queue.pop();
            if (curNode.left) queue.unshift(curNode.left);
            if (curNode.right) queue.unshift(curNode.right);
        }
        treeHeight += 1;
    }
    return treeHeight;
}

/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isBalanced = function(root) {
    if (root===null) return true;
    if (isBalanced(root.left) && isBalanced(root.right)) {
        let leftH = cntHeight(root.left);
        let rightH = cntHeight(root.right);
        console.log('root, leftH, rightH,',root, leftH, rightH);
        return Math.abs(leftH - rightH) > 1 ? false: true;
    } else {
        return false;
    }
};

/**
 * O(n)的解决方案
 * @param {TreeNode} root
 * @return {number}
 */
var countNodes = function(root) {
    if (!root) return 0;
    const leftCnt = countNodes(root.left);
    const rightCnt = countNodes(root.right);
    return leftCnt + rightCnt + 1;
};

// 验证代码
(()=>{
    const input =[2,1,3,0,7,9,1,2,null,1,0,null,null,8,8,null,null,null,null,7];
    const root = initTree(input);
    console.log('countNodes', countNodes(root));
    console.log('isBalanced', isBalanced(root));
})();

results matching ""

    No results matching ""