中文:
给定二叉树和求和,确定树是否具有根到叶路径,使得沿路径的所有值相加等于给定的总和。 注意:叶子是没有子节点的节点。 例: 鉴于以下二叉树和sum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
返回true,因为存在根到叶路径5-> 4-> 11-> 2,其中和为22。
英文:
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 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值是否刚好为0。
package cn.leetcode.easy;
import cn.kimtian.tree.TreeNode;
/**
* 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.
*
* @author kimtian
* @date 2019.01.13
* @num 112
*/
public class PathSum {
public boolean hasPathSum(TreeNode root, int sum) {
//如果根结点就为空,直接返回false
if (root == null) {
return false;
}
//每次更改总数值,为其减去当前结点的值
sum -= root.value;
//如果左右结点都为空,没有可以递归的值,则终止递归,判断最终结果是否为0
if ((root.leftNode == null) && (root.rightNode == null)) {
return (sum == 0);
}
//左右结点不为空,则递归左右结点,继续求sum值
return hasPathSum(root.leftNode, sum) || hasPathSum(root.rightNode, sum);
}
}