我已經在這個程序上工作了好幾天了,現在已經完成了大部分工作。但是,調用遞歸高度函數時會出現隨機讀取訪問錯誤。爲了解決這個問題,我一直堅持了好幾個小時,我已經多次遍歷該函數進行計數,並且似乎無法找到該錯誤的模式。我試圖通過檢查null來解決這個問題,但由於我檢查的節點甚至不等於null,所以這也失敗了。這個錯誤中最混亂的部分是它是完全隨機的。這可能是一個簡單的修復,我只是看不到。任何幫助都是極好的。隨機遞歸AVL樹高錯誤
下面是代碼
int Tree::height(Node* p)
{
int left, right;
//if node is null return 0
if (p == nullptr || p == NULL)
{
return 0;
}
這是我嘗試看看是否節點無效值。然而,這隻在有時候才起作用,因爲有時節點完全沒有價值。
//if node has invalid values, return 0
if (p->getTheData() == NULL || p->getTheData() >= 1000000000 || p- >getTheData() <= -1000000000)
{
return 0;
}
這是遞歸檢查樹時傳入不存在的節點的地方。我不知道如何或爲什麼會發生這種情況
//recursively add to the height to check the balance
left = height(p->getLLink());
right = height(p->getRLink());
if (left > right)
return left + 1;
else
return right + 1;
}
這個函數最初是什麼平衡樹。我通過節點,如果需要它然後平衡樹。
void Tree::balFactor(Node* p, int inNodeData)
{
//declare needed objects and variables
int unBalancedRight = -2;
int two = 2;
Node* rightLink;
Node* leftLink;
//check to see if node is null and set a catch case
if (p == NULL || p->getRLink() == NULL)
{
rightLink = new Node;
rightLink->setBalFac(1001);
}
//if node is valid, move right
else
{
rightLink = p->getRLink();
}
if (p == NULL || p->getLLink() == NULL)
{
leftLink = new Node;
leftLink->setBalFac(1001);
}
//if node is valid move
else
{
leftLink = p->getLLink();
}
//check to see if the node is valid
if (p != nullptr)
{
//check to see if the passed in node number is greater than the passed in data
if (inNodeData > p->getTheData())
{
//check to see if the tree needs to be balanced
if ((height(rightLink) - height(leftLink) == two))
{
//check to see what type of balancing needs to happen
if (inNodeData > p->getRLink()->getTheData())
rotateRightOnce(p);
else
rotateRightTwice(p);
}
}
//check to see in incoming data is less than p node
else if (inNodeData < p->getTheData())
{
//check to see if the data needs to be balanced
if ((height(p->getLLink() - height(p->getRLink())) == two))
{
//check to see what type of rotation needs to happen
if (inNodeData < p->getLLink()->getTheData())
rotateLeftOnce(p);
else
rotateLeftTwice(p);
}
}
//check the balance factor recursively until all nodes have been checked
balFactor(p->getLLink(), inNodeData);
balFactor(p->getRLink(), inNodeData);
}
}
讓我知道如果你需要任何其他細節
請不要修改代碼來修復錯誤,這會讓你的問題爲別人不太有用。另外請注意,您仍然遇到與其他調用高度的其他語句相同的問題。 –