完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2 个节点。
示例:
输入:1/ \2 3/ \ /4 5 6输出: 6
参考思路:
考虑到题目已知是完全二叉树,因此我们可以利用完全二叉树的性质进行解题:
- 完全二叉树除了最后一层,其他层都是满节点
- 完全二叉树的最后层左侧都是满节点
由于我们可以通过性质得到完全二叉树除了最后一层外的节点数:2^d - 1。
我们可以将问题转换为求最后一层节点的个数,我们通过二分的方式快速计算最后一层节点:
让我们思考第二个问题,最后一层的叶子节点索引在 0 到 2^d - 1之间。如何检查第 idx 节点是否存在?让我们来用二分搜索来构造从根节点到 idx 的移动序列。如,idx = 4。
- idx 位于 0,1,2,3,4,5,6,7 的后半部分,因此第一步是向右移动;
- 然后 idx 位于 4,5,6,7 的前半部分,因此第二部是向左移动;
- idx 位于 4,5 的前半部分,因此下一步是向左移动。
一次检查的时间复杂度为O(d)。
参考代码:
/**
* @param {TreeNode} root
* @return {number}
*/
var countNodes = function(root) {
if (root === null) return 0;
const computeDepth = (node) => {
let depth = 0;
while (node.left !== null) {
node = node.left;
++depth;
}
return depth;
}
const existNode = (idx, deepth, node) => {
let left = 0, right = Math.pow(2, deepth) - 1;
let pivot;
for (let i = 0; i < deepth; i++) {
pivot = left + Math.floor((right - left) / 2);
if (idx <= pivot) {
node = node.left;
right = pivot;
} else {
node = node.right;
left = pivot + 1;
}
}
return node !== null;
}
const deepth = computeDepth(root);
if (deepth === 0) return 1;
let left = 1, right = Math.pow(2, deepth) - 1;
let pivot;
while (left <= right) {
pivot = left + Math.floor((right - left) / 2);
if (existNode(pivot, deepth, root)) {
left = pivot + 1;
} else {
right = pivot - 1;
}
}
return Math.pow(2, deepth) - 1 + left;
};
复杂度分析
时间复杂度: d指的是数的高度
空间复杂度:
