题目描述:
给出一个完全二叉树,求出该树的节点个数。
说明:
完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
示例:
输入:
输出: 6
方法1:
主要思路:
(1)使用后序遍历的递归搜索,找出左子树的结点和右子树的结点,加上当前的结点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;
}
if(root->left==NULL&&root->right==NULL){
return 1;
}
int left_num=countNodes(root->left);
int right_num=countNodes(root->right);
return 1+left_num+right_num;
}
};
方法2:
主要思路:
(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 get_right_depth(TreeNode* root){
int depth=0;
while(root){
++depth;
root=root->right;
}
return depth;
}
int get_left_depth(TreeNode* root){
int depth=0;
while(root){
++depth;
root=root->left;
}
return depth;
}
int countNodes(TreeNode* root) {
if(root==NULL){
return 0;
}
int left_depth=get_left_depth(root);
int right_depth=get_right_depth(root);
if(left_depth==right_depth){
return pow(2,left_depth)-1;
}
return countNodes(root->left)+countNodes(root->right)+1;
}
};