LeetCode112. 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.
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.
有一个注意的地方,就是需要保存当前结点处的和,即从根节点到当前结点按照某一路径加起来的和。保存的话,把那个和赋给当前结点的val就行了。
每次只在遇到叶结点时,才检查那个和是否满足等于sum。
遍历的方法,用递归或者栈或者队列,深度优先,宽度优先都行。