2013-07-21 61 views
0

我有一個非常嚴重的問題。我有一棵二叉樹,當我找到一個確切的節點時,我想在樹中移動。我有這樣的代碼:功能查找節點崩潰

template<class T> 
void Tree<T>::CheckTwoTimes(Node<T> *node, Node<T> *original) 
{ 
    if(node == original) cout << "This is it" << endl; 
    CheckTwoTimes(node->Left, original); //It gives error here 
    CheckTwoTimes(node->Right, original);//And maybe it will give it here 
} 

original是我正在搜索的節點。但是,當我運行該程序時,它只是崩潰,並告訴我哪一行是問題。我不知道什麼是錯的。也許我不會像它應該那樣傳遞指針參數。

我調用該函數是這樣的:

CheckTwoTimes(root, find); //**find** is for example the most left node 
+3

你可能需要做一些空檢查,以防子女爲空。解除引用null將導致錯誤。這使我想起。你遇到了什麼錯誤? – Borgleader

+0

非常感謝。這有幫助。我沒有得到一個普通的編譯錯誤。我使用Visual Studio 2010,當我運行該程序時,它崩潰並在代碼行之前的代碼中出現一個小小的黃色箭頭。 –

回答

1

在某些時候,你會得到一個葉節點 - 當這種情況發生node將是NULL,你會嘗試取消引用它(這不好)。

您應該添加支票NULL

template<class T> 
void Tree<T>::CheckTwoTimes(Node<T> *node, Node<T> *original) 
{ 
    if (node == NULL) 
     return; 
    if (node == original) 
     cout << "This is it" << endl; 
    CheckTwoTimes(node->Left, original); 
    CheckTwoTimes(node->Right, original); 
} 

如果樹的節點是獨一無二的,它也可能是一個指針返回節點,而不是打印出來的東西是個好主意。