Given a binary tree, find all paths that sum of the nodes in the path equals to a given numbertarget.

A valid path is from root node to any of the leaf nodes.

Have you met this question in a real interview?

Yes

Example

Given a binary tree, and target =5:

     1
    / \
   2   4
  / \
 2   3

return

[
  [1, 2, 2],
  [1, 4]
]
/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param root the root of binary tree
     * @param target an integer
     * @return all valid paths
     */
    vector<vector<int>> binaryTreePathSum(TreeNode *root, int target) {
        // Write your code here
        vector<vector<int>> sols;
        vector<int> sol;
        dfs(root, target, 0, sol, sols);
        return sols;
    }

    void dfs(TreeNode *root, int target, int curSum, vector<int> &sol, vector<vector<int>> &sols) {
        if (root == NULL)
            return;
        sol.push_back(root->val);
        curSum += root->val;
        if (curSum == target && !root->left && !root->right) {
            sols.push_back(sol);
        }

        dfs(root->left, target, curSum, sol, sols);
        dfs(root->right, target, curSum, sol, sols);
        sol.pop_back();
    }
};

results matching ""

    No results matching ""