sách gpt4 ăn đã đi

java - 如何遍历 N 叉树

In lại 作者:搜寻专家 更新时间:2023-11-01 03:01:58 28 4
mua khóa gpt4 giày nike

我的树/节点类:

nhập java.util.ArrayList;
nhập java.util.List;

public class Node {
private T data;
private List<>> children;
private Node parent;

public Node(T data) {
this.data = data;
this.children = new ArrayList<>>();
}

public Node(Node node) {
this.data = (T) node.getData();
children = new ArrayList<>>();
}

public void addChild(Node child) {
child.setParent(this);
children.add(child);
}

public T getData() {
return this.data;
}

public void setData(T data) {
this.data = data;
}

public Node getParent() {
return this.parent;
}

public void setParent(Node parent) {
this.parent = cha mẹ;
}

public List<>> getChildren() {
return this.children;
}
}

我知道如何遍历二叉树,但遍历 N 元树似乎要棘手得多。

我将如何遍历这棵树。我想要一个计数器,同时遍历树以对树中的每个节点进行编号/计数。

然后在特定计数时,我可以停止并返回该计数的节点(可能删除该子树或在该位置添加子树)。

câu trả lời hay nhất

最简单的方法是实现这样的访问者模式:

public interface Visitor {
// returns true if visiting should be cancelled at this point
boolean accept(Node node);
}

public class Node {
...

// returns true if visiting was cancelled
public boolean visit(Visitor visitor) {
if(visitor.accept(this))
trả về giá trị đúng;
for(Node child : children) {
if(child.visit(visitor))
trả về giá trị đúng;
}
trả về false;
}
}

现在你可以像这样使用它:

treeRoot.visit(new Visitor() {
public boolean accept(Node node) {
System.out.println("Visiting node "+node);
trả về false;
}
});

或针对您的特定任务:

class CountVisitor implements Visitor {
int limit;
Node node;

public CountVisitor(int limit) {
this.limit = limit;
}

public boolean accept(Node node) {
if(--limit == 0) {
this.node = node;
trả về giá trị đúng;
}
trả về false;
}

public Node getNode() {
return node;
}
}

CountVisitor visitor = new CountVisitor<>(10);
if(treeRoot.visit(visitor)) {
System.out.println("Node#10 is "+visitor.getNode());
} khác {
System.out.println("Tree has less than 10 nodes");
}

关于java - 如何遍历 N 叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32795799/

28 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress