-1
我正在學習python作爲我的項目要求之一是打印二叉樹。打印樹路徑
我想出我的代碼來打印樹的路徑。 它只停留在根節點。 我想找到我搞亂的地方。
樹:
A /\ B C //\ D E F
我想輸出是:
ABD
ACE
ACF
class Node(object):
def __init__(self, data):
self.data = data
self.children = []
self.val = data
self.left = None
self.right = None
r = Node('A')
r.left = Node('B')
r.right = Node('C')
r.left.left = Node('D')
r.right.right = Node('E')
以上應r.right.left =節點( 'E) r.right.right =節點(' F「)
def binaryTreePaths(root):
results = []
c = []
binary_tree_paths(root, c, results)
return results
def binary_tree_paths(root, cand, res):
if root is None:
return
else:
cand.append(str(root.val)+" ")
if root.left is None and root.right is None:
p = ''.join(map(str, cand))
res.append(p)
binary_tree_paths(root.left, cand, res)
binary_tree_paths(root.right, cand, res)
cand.pop()
print binaryTreePaths(r)
如果它是二叉樹,你應該有左右分支而不是'children'數組。 – ozgur
@ozgur - 你是對的。初始化樹時,我弄亂了我的代碼。 – paddu
@ozgur。我修復了代碼。它仍然只打印['A B D','A C F'] – paddu