Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
return
[
[5,4,11,2],
[5,8,4,5]
]
解法1: DFS
关于求所有的路径之类的题目,首先想到的都是DFS。 这道题也不例外。 用DFS遍历tree, 每一次往下一个node, 就把当前的sum减去node的val, 如果碰到叶子并且叶子的val和所剩的val相等,则加入paths中。
C++
Java