1、給出一個完全二叉樹,求出該樹的節點個數。
說明:
完全二叉樹的定義如下:在完全二叉樹中,除了最底層節點可能沒填滿外,其餘每層節點數都達到最大值,並且最下面一層的節點都集中在該層最左邊的若干位置。若最底層爲第 h 層,則該層包含 1~ 2h 個節點。
2、示例
輸入:
1
/ \
2 3
/ \ /
4 5 6
輸出: 6
3、題解
解法一:
基本思想:遞歸,利用完美二叉樹的性質,滿二叉樹的節點總數是2^depth-1。分別求左右子樹的最大深度。
- 如果左右子樹深度是一樣的話,那麼左子樹一定是滿二叉樹,左子樹節點數2^leftdepth-1加上根節點就是2^leftdepth
- 如果左子樹深度大於右子樹深度,那麼右子樹一定是滿二叉樹,右子樹節點數2^rightdepth-1加上根節點就是2^rightdepth
解法二:
基本思想:層次遍歷,將每一層的節點數加到res
#include<iostream>
#include<vector>
#include<algorithm>
#include<deque>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
#define inf 9999
void Init_TreeNode(TreeNode** T, vector<int>& vec, int& pos)
{
if (vec[pos] == inf || vec.size() == 0)
*T = NULL;
else
{
(*T) = new TreeNode(0);
(*T)->val = vec[pos];
Init_TreeNode(&(*T)->left, vec, ++pos);
Init_TreeNode(&(*T)->right, vec, ++pos);
}
}
class Solution {
public:
int countNodes(TreeNode* root) {
//基本思想:層次遍歷,將每一層的節點數加到res
deque<TreeNode*> queue;
int res = 0;;
if (root != nullptr)
queue.push_front(root);
while (!queue.empty())
{
int len = queue.size();
res += len;
while (len--)
{
TreeNode* temp = queue.back();
queue.pop_back();
if (temp->left != nullptr)
queue.push_front(temp->left);
if (temp->right != nullptr)
queue.push_front(temp->right);
}
}
return res;
}
};
class Solution1 {
public:
int countNodes(TreeNode* root) {
//基本思想:遞歸,利用完全二叉樹的性質,滿二叉樹的節點總數是2^k-1
//分別求左右子樹的最大深度
//如果左右子樹深度是一樣的話,那麼左子樹一定是滿二叉樹,左子樹節點數2^leftdepth-1加上根節點就是2^leftdepth
//如果左子樹深度大於右子樹深度,那麼右子樹一定是滿二叉樹,右子樹節點數2^rightdepth-1加上根節點就是2^rightdepth
if (root == nullptr)
return 0;
int leftdepth = depth(root->left);
int rightdepth = depth(root->right);
if (leftdepth == rightdepth)
return pow(2, leftdepth) + countNodes(root->right);
else
return pow(2, rightdepth) + countNodes(root->left);
}
int depth(TreeNode* root)
{
int dep = 0;
while (root)
{
dep++;
root = root->left;
}
return dep;
}
};
int main()
{
Solution1 solute;
TreeNode* root = NULL;
vector<int> vec = { 1,2,4,inf,inf,5,inf,inf,3,6,inf,inf,inf };
int pos = 0;
Init_TreeNode(&root, vec, pos);
cout << solute.countNodes(root) << endl;
return 0;
}