我有一个非常严重的问题。我有一个二叉树,我想在找到一个确切的节点时在树中移动。我有这段代码:
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
最佳答案
在某些时候你会到达一个叶节点 - 当这种情况发生时 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);
}
如果树中的节点是唯一的,那么返回一个指向该节点的指针而不是输出一些东西可能也是一个好主意。
关于c++ - 查找节点崩溃的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17772680/