题目:222. 完全二叉树的节点个数
分析
-
首先我们要清楚完全二叉树和满二叉树的区别,不清楚的可以看这篇文章二叉树学习
-
普通二叉树的节点数计算如下,复杂度为O(N)
function countNodes(root){
if(root == null) return 0;
return 1 + countNodes(root.left) + countNodes(root.right);
}
- 满二叉树的节点数和树的高度呈指数关系:
function countNodes(root) {
let h = 0;
while(root) {
root = root.left;
h++;
}
return Math.pow(2, h) - 1;
}
- 完全二叉树的节点总数是普通二叉树和满二叉树的结合版,其复杂度为O(logNlogN)
function countNodes(root) {
let l = root, r = root;
let hl = 0,hr =0;
while(l) {
l = l.left;
hl++
}
while(r) {
r = r.right;
hr++;
}
// 如果左右子树的高度相同,说明是一颗满二叉树
if(hl == hr) {
return Math.pow(2, hl) - 1;
}
return 1 + countNodes(root.left) + countNodes(root.right)
};
一棵完全二叉树的两颗子树,至少有一颗是满二叉树,所以一定会触发hl==hr,只消耗O(logN)的复杂度而不会继续递归