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.
思路
题目是要求判断有没有从根节点到到叶子结点的路径上节点的值的和等于给定的sum。我们可以开始将根节点的值与给定的sum进行比较,如果不满足的话,将sum的值减去根结点的值,与下一个遍历的结点的值进行比较,依次这样遍历,只有遍历到叶子结点且sum值和该叶子结点的值匹配,则返回true。