Path Sum II @LeetCode

PROBLEM :

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

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION : (Recursive Solution)
--------------------------------------------------------------------------------

/**
 * 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) {
        vector<vector<int>> vec ;
        vector<int> row ;
        PathSumCheck(root,sum,vec,row) ;
        return vec ;
    }
   
    void PathSumCheck(TreeNode* root,int sum,vector<vector<int>> &vec,vector<int> row){
        if(root==NULL)
            return ;
           
        row.push_back(root->val) ;
        sum-=root->val ;
       
        if(sum==0&&(root->left==NULL&&root->right==NULL))
            vec.push_back(row) ;
           
        PathSumCheck(root->left,sum,vec,row) ;
        PathSumCheck(root->right,sum,vec,row) ;
    }
};

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )