Leetcode[112, 113] Path Sum

###Task1 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.

###Python

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        if not root:
            return False
        if sum == root.val and not root.left and not root.right:
            return True
        return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)

###Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
// without recursion
public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) {
        	return false;
        }
        Queue<TreeNode> nodes = new LinkedList<TreeNode>();
        Queue<Integer> values = new LinkedList<Integer>();
        nodes.offer(root);
        values.offer(root.val);

        while (!nodes.isEmpty()) {
        	TreeNode cur = nodes.poll();
        	int sumValue = values.poll();

        	if (cur.left == null && cur.right == null && sumValue == sum) {
        		return true;
        	}
        	if (cur.left != null) {
        		nodes.offer(cur.left);
        		values.offer(sumValue + cur.left.val);
        	}
        	if (cur.right != null) {
        		nodes.offer(cur.right);
        		values.offer(sumValue + cur.right.val);
        	}
        }

        return false;
    }
}

###Points

###Task2 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] ] ###Python

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: List[List[int]]
        """
        ret = []
        self.findAll(root, sum, ret, [])
        return ret
    def findAll(self, root, sum, ret, temp):
        if not root:
            return
        sum -= root.val
        temp.append(root.val)
        if sum == 0 and not root.left and not root.right:
            ret.append(temp[:])
            temp.pop()
            return
        self.findAll(root.left, sum, ret, temp)
        self.findAll(root.right, sum, ret, temp)
        temp.pop()
            

###Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

public class Solution {

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

		return;
	}

    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (root == null) {
        	return res;
        }
        List<Integer> temp = new ArrayList<Integer>();
		if (sum == root.val && root.left == null && root.right == null) {
			temp.add(root.val);
			List<Integer> saveHelper = new ArrayList<Integer>();
			saveHelper.addAll(temp);
			res.add(saveHelper);
			return res; 
		}
		temp.add(root.val);
        sumHelper(res, temp, root.left, sum - root.val);
        sumHelper(res, temp, root.right, sum - root.val);
        return res;
    }

    public static void main(String[] args) {
    	Solution sol = new Solution();
    	TreeNode root = new TreeNode(1);
    	List<List<Integer>> res = sol.pathSum(root, 1);
    	for (List<Integer> l : res) {
    		System.out.println(l);
    	}
    }
}

####or:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.*;

public class Solution {

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

		return;
	}

    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (root == null) {
        	return res;
        }
        List<Integer> temp = new ArrayList<Integer>();
		// if (sum == root.val && root.left == null && root.right == null) {
		// 	temp.add(root.val);
		// 	List<Integer> saveHelper = new ArrayList<Integer>();
		// 	saveHelper.addAll(temp);
		// 	res.add(saveHelper);
		// 	return res; 
		// }
		temp.add(root.val);
        sumHelper(res, temp, root, sum - root.val);
        return res;
    }

    public static void main(String[] args) {
    	Solution sol = new Solution();
    	TreeNode root = new TreeNode(1);
    	List<List<Integer>> res = sol.pathSum(root, 1);
    	for (List<Integer> l : res) {
    		System.out.println(l);
    	}
    }
}

###Points