题目 思路
先判断root是否为null,如果是的话直接返回false
明白返回为true的条件: (1)结点值刚好等于剩下sum值 (2)该结点是叶子,即没有左右孩子 以上两点需要同时满足
递归,需要判断root结点的左右孩子是否存在这样的结点,同时传入的参数sum=sum-root.val
代码
/** * 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.val==sum&&root.left==null&&root.right==null){ return true; } return hasPathSum(root.right,sum-root.val)||hasPathSum(root.left,sum-root.val); } }