topic
Input a binary tree and an integer, print out all paths in the binary tree where the sum of the node values is the input integer. From the root node of the tree down to the nodes passed by the leaf nodes form a path.
Python problem solving
class TreeNode(object):
def __init__(self, v=None):
self.val = v
self.left = None
self.right = None
def find_path(root, k):
res, path = [], []
cur_sum = 0
path_in_tree(root, k, cur_sum, path, res)
return res
def path_in_tree(root, k, cur_sum, path, res):
if root is None:
return
cur_sum += root.val
path.append(root)
is_leaf = root.left is None and root.right is None
if is_leaf and k == cur_sum:
res.append([v.val for v in path])
if root.left is not None:
path_in_tree(root.left, k, cur_sum, path, res)
if root.right is not None:
path_in_tree(root.right, k, cur_sum, path, res)
cur_sum -= root.val
path.remove(root)
if __name__ == '__main__':
root = TreeNode(1)
root.left = TreeNode(3)
root.right = TreeNode(4)
root.left.left = TreeNode(5)
root.right.right = TreeNode(4)
print find_path(root, 9)