leetcode Question 67: Path Sum II

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


Analysis:


Classic DFS search similar to the Question Path Sum I, in this problem we just add a vector<int> to store the result.
Details see code below:

Code(C++):


/**
 * 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:
    void ps(TreeNode* root, int sum, vector<int> path, vector<vector<int>> &res){
        if (!root){
            return;
        }else{
            path.push_back(root->val);
            if (!root->left && !root->right && sum==root->val){
                res.push_back(path);
                path.clear();
            }
            ps(root->left, sum - root->val, path, res);
            ps(root->right, sum - root->val, path, res);
        }
    }
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> res;
        vector<int>path;
        ps(root, sum, path, res);
        return res;
    }
};

Code(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 ps(self, root, sum, path, res):
        if not root:
            return
        else:
            path.append(root.val)
            if not root.left and not root.right and sum == root.val:
                res.append(path)
                path = []
            else:
                self.ps(root.left, sum - root.val, path, res)
                self.ps(root.right, sum - root.val, path, res)
    
    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: List[List[int]]
        """
        res = []
        path = []
        self.ps(root, sum, path, res)
        return res

No comments:

Post a Comment