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.
For example:Given the below binary tree and
sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
第一种解法:递归
解法二:队列
用队列来存储各个结点,当前列子存储在队列中为 5->4->8->11->13->4->7->2->1,当前结点如果是叶子结点时判断是否满足题目要求,如果满足则返回,否则继续判断队列中的下一个结点。此题是典型的宽度优先例题。细节在代码中说明。