110.222. 平衡二叉树/完全二叉树的节点个数
110
222
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++) {
const curNode = queue.pop();
if (curNode.left) queue.unshift(curNode.left);
if (curNode.right) queue.unshift(curNode.right);
}
treeHeight += 1;
}
return treeHeight;
}
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;
}
};
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));
})();