Path sum II Total accepted: 18489 total submissions: 68323my submissions
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]]
Given a binary tree and a value, find the path from the root to the leaf in the binary tree to make the total value of the node in the path
Equal to the given value
Train of Thought: DFS
Complexity: time O (n) Space O (log n)
/** * Definition for binary tree * 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<int> cur; _pathSum(root, sum,cur); return res; } private: vector<vector<int> > res; void _pathSum(TreeNode *root, int sum, vector<int> &path){ if(!root) return ; path.push_back(root->val); if(!root->left && !root->right){ if(root->val == sum) { res.push_back(path); } } _pathSum(root->left, sum - root->val, path); _pathSum(root->right, sum - root->val, path); path.pop_back(); }};
Leetcode DFS path sumii