Path Sum ---LeetCode

来源:互联网 发布:淘宝装修自定义区全屏 编辑:程序博客网 时间:2024/05/07 11:17

https://leetcode.com/problems/path-sum/

解题思路:

这道题我们通过递归,依次将 sum 的值缩减,最终判断叶子节点是否等于 sum。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public boolean hasPathSum(TreeNode root, int sum) {        if (root == null) return false;        if (root.left == null && root.right == null) return sum == root.val;        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);    }}
0 0