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) ;
}
};
---------------------------------------------------------------------------------
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
Post a Comment