将父项添加到树中的节点?

时间:2013-11-27 01:46:53

标签: java tree

我有一个树结构,我希望能够通过并将父节点添加到每个子节点拥有的数据父变量。

树的结构是:

Class Tree {
     Node root;
}

Class Node {
     String data;
     Node parent;
     List<Node> children;
}

有什么建议吗?

编辑更具体

 public void addParent() {
    for (Node child : curNode.children) {
        child.parent = curNode;
        curNode = child;
        findDFS(value);
    }
    return null;
}

使用该代码和给定的树:

     A
    /  \
   D    E
       / \
       B  S

E的父母是D,应该是A,为什么会这样?

1 个答案:

答案 0 :(得分:0)

  

E的父母是D,应该是A,为什么会这样?

在你的循环中你正在做:

for (Node child : curNode.children) {
    child.parent = curNode;
    curNode = child; // <-- problem is here!!!
    findDFS(value);
}

表示:在第一个循环中,您将子节点分配给当前节点并继续循环遍历下一个子节点,并将第一个子节点作为“父节点”,然后再次...

相关问题