LeetCode Path Sum

LeetCode 112 Path Sum
题意:
给定一个二叉树和一个和,判断从树的根结点到叶子结点的所有结点的和是否等于给定的和,如果等于返回ture,否则false
思路:递归,遍历树

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

LeetCode 113 Path Sum II
题意:
给定一棵二叉树和一个和,判断从树的根结点到叶子结点的所有结点的和是否等于给定的和,如果等于就记录这条路径。

解题思路:
  对树进行遍历,并且使用回溯法进行求解。

public class Solution {
    private List<List<Integer>> result;
    private List<Integer> l;
    private int sum;
    private int curSum = 0;

    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        result = new LinkedList<>();
        if (root == null)  return result;
        this.sum = sum;
        l = new LinkedList<>(); //不能在pathSum(TreeNode root)中声明,在下面函数中是引用调用,每次都重新声明,必然错误
        pathSum(root);
        return result;
    }

    private void pathSum(TreeNode root) {
        if (root != null) {
            l.add(root.val);
            curSum += root.val;
            if(root.left == null && root.right == null && curSum == sum){
                List<Integer> list = new LinkedList<>();
                for(Integer i : l){
                    list.add(i);
                }
                result.add(list);
            }
            if(root.left != null){
                pathSum(root.left);
            }
            if(root.right != null){
                pathSum(root.right);
            }
            curSum -= root.val;
            //删除最后一个,因为此条路不正确要回溯,如果不删除,则一直保留此节点,导致后面都不对
            l.remove(l.size() - 1);   
        }

    }
}

LeetCode 437. Path Sum III
题意:
给定一棵二叉树和一个和sum,求所有路径和为sum的个数,此路径不必从根结点开始。

public class LeetCode437 {
     public int pathSum(TreeNode root, int sum) {
         if(root == null)
             return 0;
         return pathNum(root,sum) + pathSum(root.left,sum) + pathSum(root.right,sum);
        }
     // 求从root开始的路径等于sum的个数
     public int pathNum(TreeNode root, int sum) {
         int res = 0;
         if(root == null)
             return res;
         if(root.val == sum){
             res++;
         }
         res = res + pathNum(root.left, sum - root.val) + pathNum(root.right, sum - root.val);
         return res;

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值