112. Path Sum

问题
Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

递归,如果当前节点为null则返回false。
计算并更新当前节点的值。
如果当前节点为叶节点,且当前节点的值等于target,则返回true。
递归左子节点和右子节点,返回两者的或运算。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* 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;
* }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
return hasPathSum(root,0,targetSum);
}

private boolean hasPathSum(TreeNode root, int parentVal, int target){
if (root == null){return false;}
root.val = root.val + parentVal;
if (root.left == null && root.right == null && root.val == target){
return true;
}
return ( hasPathSum(root.left, root.val, target) || hasPathSum(root.right, root.val, target));
}
}
Author

Xander

Posted on

2022-04-14

Updated on

2022-05-02

Licensed under

Comments