Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree andsum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1return true, as there exist a root-to-leaf path5->4->11->2which sum is 22.
Find all:
Return:
[
[5,4,11,2],
[5,8,4,5]
]Note
注意要到叶子结点,添加结果的条件是最后一直减完的sum和叶子结点的大小一样,不能是sum == 0,因为不然递归会直接return void
或者换一种写法,最开始进行sum的减小,在增加结果的时候多进行一次backtracking(加了的都要减回来),这样是找等于0的情况。
Code
Last updated