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.

Note: A leaf is a node with no children.

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]
]

 

Approach #1: C++. [Recursive]

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        if (root == NULL) return ans;
        vector<int> temp;
        helper(root, temp, 0, sum);
        return ans;
    }
private:
    vector<vector<int>> ans;
    
    void helper(TreeNode* root, vector<int> temp, int cur, int sum) {  
        if (root == NULL) return;
        temp.push_back(root->val);
        if (root->left == NULL && root->right == NULL && cur+root->val == sum) {
            ans.push_back(temp);
            return;
        }
        helper(root->left, temp, cur+root->val, sum);
        helper(root->right, temp, cur+root->val, sum);
    }
};

  

Approach #2: Java.[DFS+Stack]

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        int curSum = 0;
        TreeNode cur = root;
        TreeNode prev = null;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                curSum += cur.val;
                path.add(cur.val);
                cur = cur.left;
            }
            cur = stack.peek();
            if (cur.right != null & cur.right != prev) {
                cur = cur.right;
                continue;
            }
            if (cur.left == null && cur.right == null && curSum == sum)
                res.add(new ArrayList<Integer>(path));
            prev = cur;
            stack.pop();
            path.remove(path.size()-1);
            curSum -= cur.val;
            cur = null;
        }
        return res;
    }
}

  

Approach #3: Python. [BFS+Queue]

# 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]]
        """
        if root == None:
            return []
        
        res = []
        
        queue = [(root, root.val, [root.val])]
        
        while queue:
            curr, val, ls = queue.pop()
            
            if not curr.left and not curr.right and val == sum:
                res.append(ls)
            if curr.left:
                queue.append((curr.left, val+curr.left.val, ls+[curr.left.val]))
            if curr.right:
                queue.append((curr.right, val+curr.right.val, ls+[curr.right.val]))
                
        return res

  

 

posted @ 2018-12-09 21:13  Veritas_des_Liberty  阅读(201)  评论(0编辑  收藏  举报