112. 路径总和

问题:https://leetcode-cn.com/problems/path-sum/submissions/

代码:

折叠复制代码
  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public boolean hasPathSum(TreeNode root, int sum) {
  12. if(root==null){
  13. return false;
  14. }
  15. int difference = sum-root.val;
  16. if(difference==0 && root.left==null && root.right==null){
  17. return true;
  18. }
  19. if(hasPathSum(root.left,difference)){
  20. return true;
  21. }
  22. if(hasPathSum(root.right,difference)){
  23. return true;
  24. }
  25. return false;
  26. }
  27. }

思路:根据题目意思。我的想法也是穷举法,把所有路径遍历一遍判断是否符合要求。但是因为这里是一个二叉树,所以我这里使用了递归的方法来遍历。

注意:
1、java代码中有null的存在,所以不要忘记针对null的判断
2、因为要求是从根节点到叶子节点,所以在difference==0还不能直接返回true还要判断这个节点是否是叶子节点(left和right都是null)


觉得内容还不错?打赏个钢镚鼓励鼓励!!👍