问题:https://leetcode-cn.com/problems/path-sum/submissions/
代码:
/** * 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; } int difference = sum-root.val; if(difference==0 && root.left==null && root.right==null){ return true; } if(hasPathSum(root.left,difference)){ return true; } if(hasPathSum(root.right,difference)){ return true; } return false; } }
思路:根据题目意思。我的想法也是穷举法,把所有路径遍历一遍判断是否符合要求。但是因为这里是一个二叉树,所以我这里使用了递归的方法来遍历。
注意:
1、java代码中有null的存在,所以不要忘记针对null的判断
2、因为要求是从根节点到叶子节点,所以在difference==0还不能直接返回true还要判断这个节点是否是叶子节点(left和right都是null)