[英]How to find the run time of this algorithm to find if a binary tree is balanced?
這是算法
int getHeight(node *root)
{
if(!root) return 0;
return max (getHeight(root->left), getHeight(root->right)) + 1;
}
bool isBalanced(node *root)
{
if(!root) return true;
int balanceFactor = abs( getHeight (root->left) - getHeight(root->right) ); //O(logn)
if(balanceFactor > 1) return false;
return isBalanced(x->left) && isBalanced(x->right); //T(n) = 2T(n/2)
}
我的理解:
//n is the number of nodes in the tree
正如我在評論中提到的,T(n)= 2T(n / 2)+ O(logn)。 但是,我無法解決這種復發。 主定理對此不起作用。
該算法的預期運行時間為O(N平方)。 怎么了 我確定復發是錯誤的,這是肯定的。
我不確定您的復發關系,但我的簡單理解如下:
您的getHeight()函數的復雜度為O(N),因為該函數會針對以root為根的子樹中的每個節點調用一次。
出於類似的原因,在最壞的情況下,還會為每個節點調用isBalanced()函數(N次)。 同樣,在每次調用時,您都要兩次計算getHeight()函數。
Hence the complexity of isBalanced() function = O( N * (2 * N) ) = O(N^2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.