112/113 Path Sum I/II

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.

For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

思路: 用target对根节点值做减法,分别去找左子树或者右子树可能的解,递归终止条件为root.val == target&&root.left==null&&root.right==null;

public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {

        if (root == null) return false;
        if (root.left == null && root.right == null && sum == root.val) 
            return true;
        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);

    }

}

Path Sum II 思路: 找所有可能的解的集合,可以用backtracking的方法,需要借助个临时list,来存放可能的解,注意当满足条件的解,需要把list中最后一个元素remove掉,还有走到底后,也要把list中最后一个元素remove掉。

public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) return res;
        List<Integer> list = new ArrayList<>();
        findPathSum(root, sum, list, res);
        return res;
    }

    public void findPathSum(TreeNode root, int sum, List<Integer> list, List<List<Integer>> res) {
        if (root == null) return;
        list.add(root.val);
        if (root.left == null && root.right == null && root.val == sum) {
            res.add(new ArrayList<Integer>(list));
            list.remove(list.size() - 1);
            return;
        }
        if(root.left != null) findPathSum(root.left, sum-root.val, list, res);
        if (root.right != null) findPathSum(root.right, sum-root.val, list, res);
        list.remove(list.size() - 1);
        return;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s