這看起來應該很容易,但我一直有這個問題很長一段時間。正如標題所說,我只是試圖在二叉樹(不是BST!)中找到具有最小值的節點並將其返回。我可以很容易地編寫一個遞歸的void函數,它至少可以分配函數中的最小值,但是當我到達NULL指針時,我會陷入如何返回前一個節點的軌道。如何創建一個返回無序二叉樹的最小值的函數
我有一個節點類,它有一個指向左右子節點的指針,每個節點都有自己的值。這裏是我的(失敗)的嘗試至今:
int preOrder(Node *node, int value, int count, int sizeOfTree)
{
count++; //keeps track of whether or not we have traversed the whole tree
if(value < node->getValue())
value = node->getValue();
if(count == sizeOfTree);
return value;
if(node == NULL)
//Want to return to the previous function call
//How do I do this for a non void function?
//for a void function, you could jsut type "return;" and the function
//back tracks to your previous place in the tree
//but since I'm returning a value, How would I go about doing this?
//these 2 calls are incorrect but the idea is that I first traverse the left subtree
//followed by a traversal of the right subtree.
preOrder(node->getLeft(), value);
preOrder(node->getRight(), value);
}
如果可能的話,我想嘗試做這個不保持的「計數」,以及使代碼更清潔的軌道。 讓我知道是否需要澄清。
快速和骯髒的方法:創建一個靜態全局,你用'INT_MAX'初始化和你在遞歸調用覆蓋它每次找到一個小於它的值... – 2012-07-30 19:27:03
您必須使用單個「全局」計數變量,而不是按值計數。將* count *參數轉換爲指針,並在開始遍歷之前,聲明一個* count *變量,並將其地址傳遞給preOrder()。在preOrder()中,通過指針訪問這個變量,對於遞歸調用,只需傳遞* count *指針。 – 2012-07-30 19:28:01
例如類似於:preOrder(...,int * count,...){(* count)++; – 2012-07-30 19:29:08