【发布时间】:2016-11-10 05:55:52
【问题描述】:
如果有tree example
返回表单:[(depth 1, [ all items in depth 1]), (depth 2, [ all items in depth2]) ]
这个方法printitem_all_layers()应该返回[ (1,[2] ) , ( 2,[1,3] ) ]
虽然我写了一个递归方法items_at_depth(self, d),它可以返回深度为d的树的项目列表,所以我知道使用items_at_depth(self, d)实现方法printitem_all_layers()很容易。但它的效率要低得多,所以我在想如何让printitem_all_layers() 自己递归,这样我就不需要其他递归方法了
class BinarySearchTree:
def __init__(self, root):
if root is None:
self._root = None
self._left = None
self._right = None
else:
self._root = root
self._left = BinarySearchTree(None)
self._right = BinarySearchTree(None)
def is_empty(self):
return self._root is None
def items_at_depth(self, d):
"""Return a sorted list of all items in this BST at depth <d>.
Precondition: d >= 1.
@type self: BinarySearchTree
@type d: int
@rtype: list
"""
lst = []
if d - 1 >= 1 and not self._left.is_empty():
lst.extend(self._left.items_at_depth(d-1))
if d == 1 and not self.is_empty():
lst.append(self._root)
if d - 1 >= 1 and not self._right.is_empty():
lst.extend(self._right.items_at_depth(d-1))
return lst
下面是我之前所做的,没有递归
def printitem_all_layers(self):
"""Return a list of items in the tree, separated by level.
@type self: BinarySearchTree
@rtype: list[(int, list)]
"""
lst = list()
for each in range(1, self.height()+1):
lst.append(tuple((each, self.items_at_depth(each))))
return lst
【问题讨论】:
-
您能否展示您编写的函数的代码,以便我们为您指明正确的方向?
-
我认为你没有听说过breadth-first search。您可以在 Google 上搜索迭代而不是递归的相同实现。诀窍是使用队列,并用你所拥有的层深度标记你看到的每个元素。
-
我更新了问题
标签: python python-3.x recursion tree