标签:
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] ]
Subscribe to see which companies asked this question
/** * 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: void _get_path(TreeNode* root, int sum, int path_sum, vector<int> path_list, vector<vector<int>> &res_list) { if (NULL == root) { return; } path_sum = path_sum + root->val; path_list.push_back(root->val); cout << path_sum << endl; if (root->left == NULL && root->right == NULL && sum == path_sum) { res_list.push_back(path_list); } if (root->left) { _get_path(root->left, sum, path_sum, path_list, res_list); } if (root->right) { _get_path(root->right, sum, path_sum, path_list, res_list); } } vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<int> path_list; vector<vector<int>> res_list; int path_sum = 0; _get_path(root, sum, path_sum, path_list, res_list); return res_list; } };
标签:
原文地址:http://www.cnblogs.com/SpeakSoftlyLove/p/5215220.html