题目描述

题解
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val
* TreeNode left
* TreeNode right
* TreeNode() {}
* TreeNode(int val) { this.val = val
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val
* this.left = left
* this.right = right
* }
* }
*/
// DFS / 前序遍历
// 其实前中后都可以,反正DFS就行。
// 定义答案保存位boolean res初始化为false,记录一个路径和变量pathSum,每次遍历
// 当前节点就把节点值累加到sum中,并且如果当前节点是叶子节点
// (left和right都是null),判断pathSum否等于targetSum,如果
// 相等,令res等于true。否则继续递归前序遍历的左右,递归函数结束之后
// 删除刚刚累加给pathSum的结点值。
//
// 执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
// 内存消耗:38.3 MB, 在所有 Java 提交中击败了70.87%的用户
class Solution {
int pathSum = 0
int targetSum
boolean res = false
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null)
return res
this.targetSum = targetSum
preOrder(root)
return res
}
public void preOrder(TreeNode root) {
if (root == null) {
return
}
pathSum += root.val
if (root.left == null && root.right == null && pathSum == targetSum) {
res = true
}
preOrder(root.left)
preOrder(root.right)
pathSum -= root.val
}
}
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null)
return false;
if (root.left == null && root.right == null)
return targetSum == root.val;
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
}
}