[英]Inorder traversal in a BST
I have a balanced binary search tree of integers and I want to find the leftmost node which stores the integer greater or equal to a fixed number like a
using a function like ask(a)
. 我有一个整数的平衡二叉搜索树,我想找到存储整数大于或等于一个固定的数字,如最左边的节点
a
使用功能就像ask(a)
。
for example suppose that I have added the following points in my tree, 8,10,3,6,1,4,7,14,13
例如,假设我在树中添加了以下几点:
8,10,3,6,1,4,7,14,13
Then the tree would be like this: 然后树将像这样:
now ask(1)
should be 1
, ask(3)
should be 3
, ask(2)
should be 3
and so on. 现在
ask(1)
应该为1
, ask(3)
应该为3
, ask(2)
应该为3
,依此类推。
I think that I can use Inorder traversal to write my ask
function, But I don't know how. 我认为我可以使用Inorder遍历来编写我的
ask
函数,但是我不知道怎么做。
Iv written this piece of code so far: 到目前为止,IV已编写这段代码:
inorderFind(node->left, a);
if (node->key.getX() >= a)
return node;
inorderFind(node->right, a);
The first argument is the current tree node and a
is the a
that is described above. 第一个参数是当前树节点,而
a
是上面描述的a
。 I know that I can use a bool
variable like flag
and set it to true
when the if condition holds, and then it would prevent from walking through other nodes of the tree and returning a false node. 我知道我可以使用
bool
变量(例如flag
并在if条件成立时将其设置为true
,然后它将防止遍历树的其他节点并返回错误的节点。 Is there anything else that I can do? 还有什么我能做的吗?
Trees have the wonderful property of allowing queries through simple, recursive algorithms. 树具有允许通过简单的递归算法进行查询的奇妙特性。 So, let's try to find a recursive formulation of your query.
因此,让我们尝试查找查询的递归公式。
Say LEFTMOST(u)
is a function which answers this question : 说
LEFTMOST(u)
是一个可以回答这个问题的函数:
Given the binary search subtree rooted at node
u
, with(possibly null) left and right childrenl
andr
, respectively, what is the left-most node with a value>= a
?由于在节点为根的二叉搜索树
u
,与(可能为null)左右的孩子l
和r
分别是什么用值最左边的节点>= a
?
The relation is quite simple: 关系很简单:
LEFTMOST(u) = LEFTMOST(l) if it exists
LEFTMOST(r) otherwise
That's it. 而已。 How you translate this to your problem and how you handle concepts like "null" and "does not exist" is a function of your representation.
您如何将其转换为问题以及如何处理“空”和“不存在”之类的概念是您表示的一项功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.