LeetCode 112 : Path Sum 1,2,3(Java)

来源:互联网 发布:ubuntu使用方法 编辑:程序博客网 时间:2024/05/29 10:40

1、112. Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
解题思路:这道题很自然想到用递归,然而在做这道题目的时候我的递归思路陷入了僵局。我一开始的额思路是想在每个叶节点返回sum,再判断是否和给定的sum相等。这个递归思路从一开始就是错误的,因为二叉树的递归是不断把问题一分为二的过程,在每个一分为二的递归过程中都会返回一个sum,不可能实现只在叶节处返回。(现在脑子里对递归还是一坨翔的感觉)最终的实现是用递归自底向上返回当前节点左右树的Boolean的或。但是感觉这样递归可能会做很多无用的工作,比如我当前已经确定有个path为true了,那其实就没必要继续递归下去了,直接返回true就可以。然而我还不知如何才能提前终止递归,所以不知道如何优化。

/** * 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) {            if(sum - root.val == 0) {                return true;            }            else                return false;        }        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);    }}

2、113. Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
思路:递归。在写的时候要注意java中都是引用的事实,在往ret中添加结果是需要重新new一个List。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<List<Integer>> pathSum(TreeNode root, int sum) {        List<List<Integer>> ret = new ArrayList<List<Integer>>();        if(root == null) return ret;        List<Integer> subList = new LinkedList<Integer>();        helper(root, sum, subList, ret);        return ret;    }    private void helper(TreeNode root, int curLeft, List<Integer> subList, List<List<Integer>> ret) {        if(root == null) return;        subList.add(root.val);        if(root.left == null && root.right == null && root.val == curLeft) {            // 此处注意,一定要new一个LinkedList            ret.add(new LinkedList<Integer>(subList));        }        else {            helper(root.left, curLeft - root.val, subList, ret);            helper(root.right, curLeft - root.val, subList, ret);        }        subList.remove(subList.size()-1);    }}

3、437. Path Sum III
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
思路:类似于Two Sum。用一个HashMap来保存目前为止前面所有项的和以及到该和的路径个数。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int pathSum(TreeNode root, int sum) {        HashMap<Integer, Integer> preSum = new HashMap<>();        preSum.put(0, 1);        return helper(root, 0, sum, preSum);    }    private int helper(TreeNode root, int curSum, int sum, HashMap<Integer, Integer> preSum) {        if(root == null) return 0;        curSum += root.val;        int ret = preSum.getOrDefault(curSum - sum, 0);        preSum.put(curSum, preSum.getOrDefault(curSum, 0) + 1);        ret += helper(root.left, curSum, sum, preSum) + helper(root.right, curSum, sum, preSum);        preSum.put(curSum, preSum.get(curSum) - 1);        return ret;    }}
0 0
原创粉丝点击