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] ]
万万没想到啊,竟然有负数,所以剪枝条件算是错了。而且用了个全局变量,写的烂透了……
/** * 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> > re; vector<vector<int> > pathSum(TreeNode *root, int sum) { if( root == NULL)return re; vector<int> vec; path(root,sum,vec); return re; } void path(TreeNode *root, int left , vector<int> vec) { if(root == NULL)return; if(root->left == NULL && root->right == NULL) { if(left == root->val) { vec.push_back(root->val); re.push_back(vec); } } else { //if(left <= root->val)return; //else { vec.push_back(root->val); left -= root->val; path(root->left,left,vec); path(root->right,left,vec); } } } };