获取二叉树中节点索引的最简单方法 C#
Easiest way to get the index of a node in a Binary Tree c#
我想获取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。但是我想像获取数组索引一样获取节点的索引。
提前致谢。
我会尽力为您提供答案。一开始你必须把这个任务分成几个子任务:
- 如何为每个元素编制索引?
- OP 在评论中的图片中提供了答案
- 如何保存每个元素的索引?
- 可能在我添加变量的每个元素上
- 我们可以有一些
Dictionary<Node,int>
- 我要如何分配索引?
- 元素添加期间
- 将其插入变量
- 或将其插入字典
- 一旦需要,我会重新计算索引
- 更新所有项目的所有变量
- 更新字典中的所有项目
理论上的答案:但是这两种方法都需要 add Node
和 recalculate all the indexes
之后。您基本上需要创建遍历树中每个元素的方法,从最低值到最高值并将其索引保存在某处。
我们可以借用那里迭代树的答案:
- How do I iterate over Binary Tree?
- 或Traversing a tree of objects in c#
我想获取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。但是我想像获取数组索引一样获取节点的索引。
提前致谢。
我会尽力为您提供答案。一开始你必须把这个任务分成几个子任务:
- 如何为每个元素编制索引?
- OP 在评论中的图片中提供了答案
- 如何保存每个元素的索引?
- 可能在我添加变量的每个元素上
- 我们可以有一些
Dictionary<Node,int>
- 我要如何分配索引?
- 元素添加期间
- 将其插入变量
- 或将其插入字典
- 一旦需要,我会重新计算索引
- 更新所有项目的所有变量
- 更新字典中的所有项目
- 元素添加期间
理论上的答案:但是这两种方法都需要 add Node
和 recalculate all the indexes
之后。您基本上需要创建遍历树中每个元素的方法,从最低值到最高值并将其索引保存在某处。
我们可以借用那里迭代树的答案:
- How do I iterate over Binary Tree?
- 或Traversing a tree of objects in c#