我現在已經建立了一個AVL樹第k個分節點,這裏是一個函數來找到第k個分節點AVL樹 (K從0開始) 代碼:查找AVL樹
int kthMin(int k)
{
int input=k+1;
int count=0;
return KthElement(root,count,input);
}
int KthElement(IAVLTreeNode * root, int count, int k)
{
if(root)
{
KthElement(root->getLeft(), count,k);
count ++;
if(count == k)
return root->getKey();
KthElement(root->getRight(),count,k);
}
return NULL;
}
它可以找到一些正確的節點,但有些可能會失敗,任何人都可以幫助我調試此問題> THanks
Hi Duke,感謝您的建議,我現在發現了這個bug,似乎在一些遞歸調用之後,最終的返回值總是最後一行「return NULL」。我現在在行下使用了一個私有變量「int kth」if(count == k)kth = root-> getKey();然後在第一個Kthmin函數中返回第k個。然後問題解決了。 – user2840454