Given a complete binary tree, count the number of nodes.
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Subscribe to see which companies asked this question
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
int countNodesHelper(TreeNode* root, int curLevel, int treeHight) {
if (curLevel == treeHight)
return 1;
int righTreeMostLevel = (root->right != NULL)? leftMostLevel(root->right, curLevel+1) : curLevel;
if (righTreeMostLevel == treeHight)//如果右子树的最左子树能到达全树的高度
{
//则,左子树就是一颗满的二叉树,并且左子树的高度为treeHight-curLevel, 节点数目为 2e(treeHight-curLevel)-1; 再加上root节点, 数目为 2e(treeHight-curLevel)
return (1 << (treeHight-curLevel)) + countNodesHelper(root->right, curLevel+1, treeHight);
}
else // 如果右子树的最左子树不能达到全树的高度,
{
//则,右子树一定是一个满的二叉树,并且右子树的高度为 treeHight-curLevel-1, 节点数目为2e(treeHight-curLevel-1)-1,
//再加上root节点,数目为2e(treeHight-curLevel-1)
return (1 << (treeHight-curLevel-1) + countNodesHelper(root->left, curLevel+1, treeHight));
}
}
int leftMostLevel(TreeNode* root, int level) {
TreeNode* curNode = root;
int curLevel = level;
while (curNode->left)
{
curLevel++;
curNode = curNode->left;
}
return curLevel;
}
int TreeHight(TreeNode *root) {
if (root == NULL)
return 0;
int leftHight = TreeHight(root->left);
int rightHight = TreeHight(root->right);
return max(leftHight, rightHight)+1;
}
int fTreeHt(TreeNode *root){ //get the height of a complete binary tree.
if(!root) return 0;
return 1+fTreeHt(root->left);
}
public:
int countNodes(TreeNode* root) {
if(!root) return 0;
//要获取左右子树的高度
int lh=fTreeHt(root->left);
int rh=fTreeHt(root->right);
if(lh==rh)
return (1<<lh)+countNodes(root->right); /*1(根节点) + (1<<lh)-1(完全左子树) + # of rightNode */
else
return (1<<rh)+countNodes(root->left); /*1(根节点) + (1<<rh)-1(完全右子树) + # of leftNode*/
}
/*
int countNodes(TreeNode* root) {
if (root == NULL)
return 0;
int h = TreeHight(root);
return countNodesHelper(root, 1, h);
}
*/
};