题目描述:
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.
Hide Tags Tree Binary Search
分析:
由于是二叉搜索树,那么就满足完全二叉树的结构。只有可能最后一层的右边会少几个结点。
因此,如果是满二叉树的话,只需要求出整颗二叉搜索树的层数h,然后利用满二叉树的性质:节点数为2^h-1。
否则就只有分别求出左子树的结点数与右子树的结点数之和了。求这两个字数的结点数的方法和判断根节点一样,也是先判断是否是满二叉树,即递归调用即可。
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.
Hide Tags Tree Binary Search
分析:
由于是二叉搜索树,那么就满足完全二叉树的结构。只有可能最后一层的右边会少几个结点。
因此,如果是满二叉树的话,只需要求出整颗二叉搜索树的层数h,然后利用满二叉树的性质:节点数为2^h-1。
否则就只有分别求出左子树的结点数与右子树的结点数之和了。求这两个字数的结点数的方法和判断根节点一样,也是先判断是否是满二叉树,即递归调用即可。
以下是C++实习代码:
/**//84ms*/
/**
* 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 lef_height(TreeNode* root){ //求出左子树的最大层次
int cnt = 0;
while(root != NULL){
cnt++;
root = root->left;
}
return cnt;
}
int rig_height(TreeNode* root){ //求出右子树的最大层次
int cnt = 0;
while(root != NULL){
cnt++;
root = root->right;
}
return cnt;
}
int countNodes(TreeNode* root) {
int cnt = 0;
if(root == NULL)
return cnt;
int lef = lef_height(root);
int rig = rig_height(root);
if(lef == rig) //左右子树的层次是相等的,说明是满二叉树,直接用公式计算节点总数
return (1<<lef)-1;
else //不是满二叉数,那么递归调用计算出左右字数的结点数再加上根节点数即可
return countNodes(root->left) + countNodes(root->right) + 1;
}
};