使用前序遍历可以获得所有到达叶子结点的路径
注:代码中使用的Tree2类可以从链接中获取
# form a binary tree
import Tree2
tree = Tree2.BinTree()
for i in range(1,9):
tree.add(i)
tree.add(10)
tree.add(9)
# tree.out_value_levelorder()
# find a path, sums of nums in these paths equal the target value
from collections import deque # Double ended queue, STL
def FindAllPath(rootnode,expectednum):
if not rootnode:
return
currentsum=0
path = deque()
searchpath(rootnode,expectednum,currentsum,path)
def searchpath(rootnode,expectednum,currentsum,path):
currentsum+=rootnode.data
path.append(rootnode.data)
# print(path)
notleaf = rootnode.left and rootnode.right
if (not notleaf and currentsum==expectednum):
print('find a path and now printing...')
for value in path:
print(value)
if (rootnode.left):
searchpath(rootnode.left,expectednum,currentsum,path)
if (rootnode.right):
searchpath(rootnode.right,expectednum,currentsum,path)
# if run there, mean counter leaf node
# print('is leaf')
# if arrive leaf node and path do not satisfy, trackback currentsum and path
currentsum-=rootnode.data
path.pop()
# test
FindAllPath(tree.root,17)