【发布时间】:2020-12-15 11:56:19
【问题描述】:
我想获取 bst 中所有节点的索引。我用来插入值和搜索节点的代码是
public class BTS
{
public class Node
{
public int value;
public Node Left;
public Node Right;
}
public Node Insert(Node nod,int value)
{
if (nod == null)
{
nod = new Node();
nod.value = value;
}
else if(value < nod.value)
{
nod.Left = Insert(nod.Left, value);
}
else if(value > nod.value)
{
nod.Right = Insert(nod.Right, value);
}
return nod;
}
public string FindNode(Node node, int s)
{
string Output = "";
if (node == null)
return Output = "not found";
else if (s.CompareTo(node.value) < 0)
return FindNode(node.Left, s);
else if (s.CompareTo(node.value) > 0)
return FindNode(node.Right, s);
return Output = "found";
}
static void Main()
{
Node N = null;
BTS bs = new BTS();
N = bs.Insert(N, 10);
N = bs.Insert(N, 9);
N = bs.Insert(N, 8);
N = bs.Insert(N, 11);
N = bs.Insert(N, 12);
bs.FindNode(N,9);
}
}
如果节点 9 存在,上面的代码给我的值为 true。但我想获取节点的索引,就像我们获取数组索引一样。
提前谢谢你。
【问题讨论】:
-
你试过什么?你是如何处理这个寻找索引的?解决过程中遇到了什么问题?
-
您想访问像 bs[2] 这样的节点,或者您想知道值为 2 的节点的“索引”?
-
第二个问题是,索引到底是什么意思?如果你用谷歌搜索
binary tree image,中间的那些元素应该返回什么索引?这是您必须插入逻辑并决定如何搜索该树的地方。如果从底部到顶部或顶部到底部。如果你计算子节点或者你会考虑它有多远。如果您将引入自己的属性并将其设置为增量元素只是为了获得一些数字。有很多可能性,你应该从尝试一些开始。 -
我在 c# 中找不到任何与此相关的答案或无法实现,这就是我在论坛@Tatranskymedved 中询问的原因
-
节点 9 的索引是多少?
标签: c# binary-tree