Appearance
222.完全二叉树的节点个数
js
/**
* @param {TreeNode} root
* @return {number}
*/
var countNodes = function (root) {
if (!root) return 0;
let left = root.left;
let right = root.right;
let leftHeight = 0;
let rightHeight = 0;
while (left) {
left = left.left;
leftHeight++;
}
while (right) {
right = right.right;
rightHeight++;
}
// 如果是个满二叉树,最左边和最右边的节点高度相同
if (leftHeight === rightHeight) {
// 满二叉树节点个数 2^k - 1
return Math.pow(2, rightHeight + 1) - 1;
}
return countNodes(root.left) + countNodes(root.right) + 1;
};
/**
* @param {TreeNode} root
* @return {number}
*/
var countNodes = function (root) {
if (!root) return 0;
let left = root.left;
let right = root.right;
let leftHeight = 0;
let rightHeight = 0;
while (left) {
left = left.left;
leftHeight++;
}
while (right) {
right = right.right;
rightHeight++;
}
// 如果是个满二叉树,最左边和最右边的节点高度相同
if (leftHeight === rightHeight) {
// 满二叉树节点个数 2^k - 1
return Math.pow(2, rightHeight + 1) - 1;
}
return countNodes(root.left) + countNodes(root.right) + 1;
};