以递归方式将树元素添加到新列表中

时间:2014-11-08 00:17:16

标签: java list recursion binary-search-tree

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

1 个答案:

答案 0 :(得分:0)

您可以通过两种方式遍历树。这两个遍历首先是深度优先,然后是广度。 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) 

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