基本上我的問題是,我需要一個ADDNODE方法,它的簽名是這樣的:遞歸二叉樹
addNode(Node thisNode, Node toAdd)
我目前的方法簽名是:
AddRecursively(null, usersInput);
空(節點),因爲它是我需要將值傳遞迴方法的遞歸方法。 usersInput是一個int。
我很笨,如何做仍然使用遞歸的時候被告知要做的事情。
請注意: 請嘗試以簡單的方式解釋您的代碼,如果可能的話,我在編程方面不是太好。
我的代碼應該工作,因爲它是基於我的舊代碼,它確實工作,但我還沒有測試它,Node findNode已被留下,因爲我應該使用兩個節點,但我很笨怎麼辦這是非常誠實的。
public void AddRecursively(Node findNode, Node findNextNode, int usersInput)//don't need findNode i think
{
if (root.value == null)
{
root.value = usersInput; //if no root, make it (everytime it is run it will have no root)
}
else if (usersInput > root.value && root.right == null)
{
root.right.value = usersInput; //first right of node
}
else if (usersInput < root.value && root.left == null)
{
root.left.value = usersInput; //first left of node
}
//recursive
else if (usersInput > root.right.value && root.right != null && findNextNode == null)
{
findNextNode = root.right; //setting up recursive right
}
else if (usersInput < root.left.value && root.left != null && findNextNode == null)
{
findNextNode = root.left; //setting up recursive left
}
//adding values before doing recursive
else if (usersInput > findNextNode.right.value && findNextNode.right == null)
{
findNextNode.right.value = usersInput; //if the next right is empty add
}
else if (usersInput < findNextNode.left.value && findNextNode.left == null)
{
findNextNode.left.value = usersInput; //if next left is empty add
}
//recursive, should be able to handle left.left.right for example as findNextNode could be right.right then it could = right.right.left
else if (usersInput > findNextNode.right.value && findNextNode.right != null)
{
findNextNode = findNextNode.right;
AddRecursively(null, findNextNode, usersInput);
}
else if (usersInput < findNextNode.left.value && findNextNode.left != null)
{
findNextNode = findNextNode.left;
AddRecursively(null, findNextNode, usersInput);
}
}
我不太明白這個問題,你的代碼不起作用? –
@AlejandroPiad我的代碼確實有效,但它並不包含兩個輸入節點,它們是add方法所在的節點和下一個要訪問的節點。目前只需要進入哪個節點..對不起,這是一個措辭嚴厲的帖子!我只是不太確定自己該說甚麼。我的代碼唯一的問題是它沒有像主要開發人員想要的那樣完成。(我正在學習c#) – Zain
遞歸是一種以簡潔的方式編寫難度代碼的方法。這件藝術品看起來像是一件很難寫的東西:-) – lboshuizen