问题描述:
Given a complete binary tree, count the number of nodes.
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 2^h nodes inclusive at the last level h.
求完全二叉树中的节点数。
问题求解:
满二叉树的节点数为2^h - 1
,利用完全二叉树与满二叉树的关系。
做2的幂时不要用pow(),这样会超时。用1 << height这个方法来得到2的幂。
(1)完全二叉树的一个性质是,如果左子树最左边的深度,等于右子树最右边的深度,说明这个二叉树是满的。则可利用公式求解。
(2)如果两边深度不等,则分别求解左右子树节点数,再加上根节点。
复杂度:时间 O(h^2), 空间 O(1)。
方法一:
/**
* 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 {
public:
int countNodes(TreeNode* root) {
if(root == NULL) return 0;
int lheight = getLeftHeight(root);//(1)左子树最左边高度
int rheight = getRightHeight(root);//(2)右子树最右边高度
//(3)判断是否为满二叉树
if(lheight == rheight)
{//满二叉树。节点一共有2^h - 1个,h为高度
return (1<<lheight) - 1;//左移一位相当于乘2,2^h即等于1<<h!!!
}
else
{//非满二叉树。递归求左右子树节点数+根节点
return countNodes(root->left) + countNodes(root->right) +1;//加上根节点
}
}
//迭代版本
int getLeftHeight(TreeNode* root)
{//得到完全二叉树左子树最左边深度(高度)
int hl=0;
while(root)
{
hl++;
root = root->left;
}
return hl;
}
int getRightHeight(TreeNode* root)
{//得到完全二叉树右子树最右边深度(高度)
int hr=0;
while(root)
{
hr++;
root = root->right;
}
return hr;
}
};
方法二:
/**
* 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 {
public:
int countNodes(TreeNode* root) {
if(root == NULL) return 0;
int lheight = getLeftHeight(root);//(1)左子树最左边高度
int rheight = getRightHeight(root);//(2)右子树最右边高度
//(3)判断是否为满二叉树
if(lheight == rheight)
{//满二叉树。节点一共有2^h - 1个,h为高度
return (1<<lheight) - 1;//左移一位相当于乘2,2^h即等于1<<h!!!
}
else
{//非满二叉树。递归求左右子树节点数+根节点
return countNodes(root->left) + countNodes(root->right) +1;//加上根节点
}
}
//递归版本
int getLeftHeight(TreeNode* root)
{//得到完全二叉树左子树最左边深度(高度)
return root==NULL?0:1+getLeftHeight(root->left);
}
int getRightHeight(TreeNode* root)
{//得到完全二叉树右子树最右边深度(高度)
return root==NULL?0:1+getRightHeight(root->right);
}
};