问题描述
给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。
完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
代码
方案一:不讲码德版本 时间复杂度为O(n)
var countNodes = function(root) {
if(!root) return 0;
return countNodes(root.left) + countNodes(root.right) + 1;
};
方案二:
var countNodes = function(root) {
if(!root) return 0;
const getDepth = function(node) {
let depth = 0;
while(node) {
depth++;
node = node.left;
}
return depth;
}
let leftdepth = getDepth(root.left);
let rightdepth = getDepth(root.right);
if(leftdepth == rightdepth) {
return (1<<leftdepth+1 - 1) + countNodes(root.right);
}else {
return (1<<rightdepth+1 - 1) + countNodes(root.left);
}
};
完全二叉树的特点:
1.叶子结点只可能在最大两层出现
2.对任意一结点,如果其右子树的最大层次为L,则其左子树的最大层次为L或者L+1(子树必须向左对其)
3.度为1 的结点只有0个或1个
完全二叉树左右子树等高时,则左子树一定是满二叉树,右子树有一个度为1的节点。
当左右子树不等高时,右子树一定是满二叉树,左子树是满二叉树或有1个度为1的节点