问题 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 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)); } }