如何定位或获取树中子节点的父节点

huangapple go评论96阅读模式
英文:

How do I locate or get parent of child in tree

问题

我正在根据类似这样的文本文件构建一棵树:

Store, manager, employee
manager, smith, Michael
employee, steve, karen, litt, kwan

我的代码大致如下:

读取第一行;
将第一个字符串设为父节点,后续字符串设为子节点
读取第二行,将第一个字符串设为父节点,后续字符串设为子节点

但我想在读取第二行时,检查第一个字符串是否是上面字符串中的子节点,并将第一个字符串(第二行的父节点)赋值给那个子节点,以实现以下树形结构:

        Store
          /
    manager - employee
      /              \
  smith - Michael     steve - karen - litt - kwan

我无法弄清楚检查字符串的父节点是否是先前任何字符串的子节点,并将其设置为该子节点的部分。

英文:

I am making a tree from a text file like this:

Store, manager, employee
manager, smith, Michael
employee, steve, karen, litt, kwan

my code is something like this:

reads first line;
sets first string to parent and following to children
reads second line, sets first string to parent and following to children

But I want to read the second line, see if the first string is children in above string, and assign the value the first string(parent of second line) to that children to achieve a tree structure like this:

        Store
          /
    manager - employee
      /              \
  smith - Michael     steve - karen - litt - kwan

I cannot figure out the part where I check if the parent of the string is a child of any previous string and set it to that child

答案1

得分: 1

你可以使用 HashMap。假设你有一个类似这样的 Node 类:

class Node{
   String value;
   Node parent;
   Node[] children;
}

在构建树的时候,你可以构建一个 HashMap<String, Node>,将字符串值映射到节点对象上。

然后你可以通过检查 map.get(stringValue) == null 来判断 stringValue 是否是上述字符串的子节点。

英文:

You can use a HashMap.
Suppose you have a Node class like this:

class Node{
   String value;
   Node parent;
   Node[] children;
}

When you construct you tree,You can construct a HashMap&lt;String,Node&gt; to map the string value to the Node Object.

Then you can check map.get(stringValue)==null to see if the stringValue is a child of above String.

huangapple
  • 本文由 发表于 2020年10月8日 08:41:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/64254209.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定