Description:
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.
算法分析:
注意完全二叉樹的定義和滿二叉樹是有區別的。
對完全二叉樹前序遍歷時,有值得節點先於空節點遍歷。
一個完全二叉樹左右子樹至少有一個是滿二叉樹。
滿二叉樹的節點數是2^k-1,k是樹的深度。
所以我們可以先判斷該樹是否爲滿二叉樹,然後是的話直接返回結果,如果不是遞歸地求解子樹。
這樣不用遍歷所有的節點。複雜度小於O(N),比對所有點遍歷複雜度要小,最好的情況是O(lgN)。
推算大概在O(lgN)~O(N)之間。
具體的分析,取左右子樹只有一個是滿樹的最差情況。
T(N) = lg(N/2) + T(N/2)
T(1) =1
可以推導下複雜度最差在O(lgN*lgN)。
代碼如下:
/**
* 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 nodesofMan(TreeNode* root){ //判斷是否爲滿二叉樹,若是返回該滿二叉樹的節點數。
int l=1,r=1;
TreeNode *node = root;
while(node->left)
{
l++;
node = node->left;
}
node = root;
while(node->right)
{
r++;
node = node->right;
}
if(l == r)
return (int)pow(2,(double)l) - 1;
else
return 0;
}
int countNodes(TreeNode* root) {
if(root == NULL) return 0;
//else if(root->left == NULL) return 1;
if(nodesofMan(root)) return nodesofMan(root);
else
return countNodes(root->left) + countNodes(root->right) +1;
}
};