【问题标题】:adding tree elements into a new list recursively-java递归地将树元素添加到新列表中-java
【发布时间】:2014-11-08 00:17:15
【问题描述】:

如何递归地将多态树的所有元素添加到列表中?以及如何遍历整个多态树?

【问题讨论】:

  • 首先您要选择遍历树的方式。例如depth-firstbreadth first。尝试理解维基百科链接中的示例,您将很好地了解如何实现遍历。之后将元素放入列表是一个简单的list.add(element),例如ArrayList。在那里,多态性开始发挥作用。如果你真的想要列表中的所有种可能的类型,你可以使用ArrayList<Object>

标签: java list recursion binary-search-tree


【解决方案1】:

您有两个选项可以遍历树。这两个遍历是深度优先和广度优先。 This 展示了每个遍历的基本原理。 基础是:

depth-first: 
Visit the starting vertex
Proceed as far as possible along a given path (via a neighbor) before “backtracking” and going along the next path

breadth-first:
visit the starting vertex
visit all of its neighbors
visit all unvisited vertices 2 edges away
visit all unvisited vertices 3 edges away, etc

每次运行时间为:

Let V = number of vertices in the graph, and E = number of edges

A traversal requires O(V + E) steps.
for a dense graph, E->V2, so the worst-case bound is  O(V2)
for a sparse graph, O(V + E) << O(V2) 

在您的递归遍历代码中,您可以将每个节点添加到列表/哈希映射中以存储信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    相关资源
    最近更新 更多