我想写一个函数,它返回列表中树中的所有元素。尽管我不允许使用全局变量。下面是我的尝试:遍历一棵树
def traverse(current node):
if no left child and no right child:
return current nodes data
else:
if both left child and right child exist:
return [current nodes data,left_child.traverse(),right_child._traverse()]
elif no left child: return [current node's data,right_child.traverse()]
elif no right child: return [current node's data,left_child.traverse()]
我们用这个例子:(根2,左边的孩子是1,右孩子是3,右小孩的权利小孩4)
2
1 3
4
呼吁横向上这棵树返回此:
[2, 1, [3, 4]]
所以,唯一的问题是,我们不能把一切以适应只有一个列表中。
编辑:这里是一些节点功能,这可以被称为: node.data
,node.left
,node.right
你能添加代码的节点呢? – Moshe 2013-04-05 03:18:35