[英]Return pointer to nth node in level-ordered binary tree
假设我按级别顺序有这个二叉树:
我想返回一个指向第5个节点的指针。 我在构造函数时遇到了麻烦。
这是我到目前为止的内容:
Node* GetNodeAtCount(Node *r, int x)
{
if(r != NULL)
{
if(r->count == x) {return r;}
else
{
GetNodeAtCount(r->left, x); // my problem is here
GetNodeAtCount(r->right, x);
}
}
}
我的函数只能正确返回树的右侧。 我无法找出一种方法来分别调用递归函数,因为我无法通过比较“大于”或“小于”来进行过滤,即转到右子树,左子树等。
我不熟悉C ++,因此这将是伪代码:
If the current node does not exists:
return failure
If (the node is the one you are after):
return the current node
result=recurse(left node)
if result != failure:
return result
return recurse(right node) // which may be failure
编辑后,在开始时添加“当前节点不存在”的检查; 这简化了其余的代码。 我认为在C ++中,您将其与null对象进行比较?
如果您的树是按计数排序的,则可以从此处进行比较和分支:
else if (x < r->count && r->left != NULL) { return GetNodeAtCount(r->left, x); }
else if (x > r->count && r->right != NULL) { return GetNodeAtCount(r->right, x); }
else { return NULL; }
不要忘记检查r-> left和r-> right的NULL值! 注意这些行中的返回调用。
如果您的树未按计数排序,则必须检查返回值。
else
{
Node *ret;
ret = (r->left != null ? GetNodeAtCount(r->left, x) : NULL);
ret = (ret == NULL && r->right != null ? GetNodeAtCount(r->right, x) : ret);
return ret;
}
但是,如果使用的树没有排序,则应重新考虑数据结构,并可能使用更合适的方法。 甚至向量/数组也将比搜索未排序的树更快。 如果由于要对其他字段进行排序而使用树,则考虑使用B +树。
您需要递归地调用左侧的树,也许这样会起作用-
Node* GetNodeAtCount(Node *r, int x)
{
if(r != NULL)
{
if(r->count == x) {return r;}
Node *temp = GetNodeAtCount(r->right, x); //check right tree for match
if (temp != NULL)
return temp;
return GetNodeAtCount(r->left, x); // if right tree does not match further go into left tree
}
return NULL //return NULL if it is the end of tree so that the check temp != NULL will work correctly
}
让我知道这是否对您有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.