2015年6月9日星期二

Path Sum II leetcode

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1
return
[
   [5,4,11,2],
   [5,8,4,5]
]
一般求结果的都用递归求解 这里的时间复杂度仍然只是一次遍历O(n),而空间复杂度则取决于满足条件的路径和的数量(假设是k条),则空间是O(klogn)。

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

没有评论:

发表评论