【LeetCode】 112. Path Sum 路径总和(Easy)(JAVA)
题目地址: https://leetcode.com/problems/path-sum/
题目描述:
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.
题目大意
给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
说明: 叶子节点是指没有子节点的节点。
解题方法
1、这一题其实和上一题类似 【LeetCode】 111. Minimum Depth of Binary Tree 二叉树的最小深度(Easy)(JAVA)
2、不断迭代到叶子节点即可
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) return false;
if (root.left == null && root.right == null) return root.val == sum;
if (root.left == null) return hasPathSum(root.right, sum - root.val);
if (root.right == null) return hasPathSum(root.left, sum - root.val);
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
}
执行用时 : 0 ms, 在所有 Java 提交中击败了 100.00% 的用户
内存消耗 : 39.4 MB, 在所有 Java 提交中击败了 6.52% 的用户