【问题标题】:Easiest way to get the index of a node in a Binary Tree c#获取二叉树c#中节点索引的最简单方法
【发布时间】: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


【解决方案1】:

我会尽力为您提供答案。一开始你必须把这个任务分成几个子任务:

  • 如何索引每个元素?
    • OP 在 cmets 中的图像中提供了答案
  • 如何保存每个元素的索引?
    • 可能在我添加变量的每个元素上
    • 我们可以有一些Dictionary&lt;Node,int&gt;
  • 我将如何分配索引?
    • 在元素添加期间
      • 将其插入到变量中
      • 或将其插入字典
    • 一旦需要,我会重新计算索引
      • 更新所有项目的所有变量
      • 更新字典中的所有项目

理论上的答案:这两种方法都需要add Noderecalculate all the indexes 之后。您基本上需要创建遍历树中每个元素的方法,从最低值到最高值并将其索引保存在某处。

我们可以借用那里迭代树的答案:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 2021-07-10
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多