leetcode 113. 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.
Note: A leaf is a node with no children.
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] ]
思路:回溯,(DFS)
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 private: 12 bool isLeaf(TreeNode *root) { 13 return (root->left == NULL) && (root->right == NULL); 14 } 15 void dfs(TreeNode *root, int sum, vector<vector<int> > &res, vector<int> &v) { 16 if (root == NULL) { 17 return ; 18 } 19 v.push_back(root->val); 20 if (isLeaf(root) && sum == root->val) { 21 res.push_back(v); 22 } 23 dfs(root->left, sum - root->val, res, v); 24 dfs(root->right, sum - root->val, res, v); 25 v.pop_back(); 26 } 27 public: 28 vector<vector<int>> pathSum(TreeNode* root, int sum) { 29 vector<vector<int> > res; 30 vector<int> v; 31 dfs(root, sum, res, v); 32 return res; 33 } 34 };
越努力,越幸运