【发布时间】:2018-02-02 18:56:00
【问题描述】:
我之前发布了一个与此主题相关的问题,但我也无法弄清楚这一点。我正在尝试通过键值搜索无序二叉树并通过递归函数返回其关联值。
该类具有以下形式:
Class Node
{
private:
Node *leftChild;
Node *rightChild;
int key;
int value;
}
每个变量都有相关的 get 方法。所以我基本上想搜索二叉树并在到达正确的节点后返回它的值。
这是我迄今为止的尝试,我想我已经很接近了:
int preOrder(Node *node, int key)
{
if(node->getKey() == key)
return node->getValue();
Node* leftNode = node->getLeft();
if(leftNode != NULL)
{
return preOrder(leftNode, key);
}
Node* rightNode = node->getRight();
if(rightNode != NULL)
{
return preOrder(rightNode, key);
}
//I know a return statement needs to be placed here
//in case both pointers are NULL in order to return to the previous
//node in the tree, but I'm not sure how to do this...
}
有人有什么建议吗?
【问题讨论】:
-
等一下,我会挖掘出我在你上一个问题上写的课程。
-
一条建议:使用有序树!
标签: c++ tree binary-tree