leetcode-112 路径总和
计算根节点到叶子节点的和,然后和目标值进行比较。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private boolean flag = false;
public void findPath(TreeNode root, int curSum, int aim){
// 找到了目标值,不在遍历
if (flag) return;
if (root.left == null && root.right == null){
if (curSum + root.val == aim) flag = true;
return ;
}
if (root.left != null) findPath(root.left, curSum + root.val, aim);
if (root.right != null) findPath(root.right, curSum + root.val, aim);
}
public boolean hasPathSum(TreeNode root, int sum) {
// 判空!!! 又忘了
if (root == null) return false;
findPath(root, 0, sum);
return flag;
}
}