gpt4 book ai didi

java - 如何获取树的所有叶节点?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:43:13 25 4
gpt4 key购买 nike

假设我在一棵树中有一个节点,如何获取所有祖先为该节点的叶节点?

我已经这样定义了 TreeNode:

public class TreeNode<T>
{
/** all children of the node */
private List<TreeNode<T>> children = new ArrayList<TreeNode<T>>();
/** the parent of the node, if the node is root, parent = null */
private TreeNode<T> parent = null;
/** the stored data of the node */
private T data = null;

/** the method I want to implement */
public Set<TreeNode<T>> getAllLeafNodes()
{
Set<TreeNode<T>> leafNodes = new HashSet<TreeNode<T>>();
return leafNodes;
}
}

最佳答案

使用递归。

  • 如果节点本身是一片叶子,则返回它
  • 否则,返回其子节点的所有叶节点

像这样(未测试):

public Set<TreeNode<T>> getAllLeafNodes() {
Set<TreeNode<T>> leafNodes = new HashSet<TreeNode<T>>();
if (this.children.isEmpty()) {
leafNodes.add(this);
} else {
for (TreeNode<T> child : this.children) {
leafNodes.addAll(child.getAllLeafNodes());
}
}
return leafNodes;
}

关于java - 如何获取树的所有叶节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31384894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com