标签:style blog http io ar color sp for on
和上一题类似,这里是要记录每条路径并返回结果。
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: void pathSum(TreeNode *root, vector<vector<int> > &ans, vector<int> tmp, int subsum, int sum) { if (!root) return ; if (!root -> left && !root -> right && subsum + root -> val == sum) { tmp.push_back(root -> val); ans.push_back(tmp); } if (root -> left) { tmp.push_back(root -> val); subsum += root -> val; pathSum(root -> left, ans, tmp, subsum, sum); tmp.pop_back(); //因为判断右子树的时候不需要左子树的和 subsum -= root -> val; } if (root -> right) { tmp.push_back(root -> val); subsum += root -> val; pathSum(root -> right, ans, tmp, subsum, sum); } } vector<vector<int> > pathSum(TreeNode *root, int sum) { vector<vector<int> > ans; vector<int> tmp; pathSum(root, ans, tmp, 0, sum); return ans; } };
其实效率好一些的是对tmp传入引用,例如vector<int> &tmp,那么此时每次记录结果或者左右递归之后都要有一个pop值,来保证tmp符合当前的要求:详见
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void pathSum(TreeNode *root, vector<vector<int> > &ans, vector<int> &tmp, int subsum, int sum) { if (!root) return ; if (!root -> left && !root -> right && subsum + root -> val == sum) { tmp.push_back(root -> val); ans.push_back(tmp); tmp.pop_back(); // 保持tmp } if (root -> left) { tmp.push_back(root -> val); subsum += root -> val; pathSum(root -> left, ans, tmp, subsum, sum); tmp.pop_back(); // 因为判断右子树的时候不需要左子树的和 subsum -= root -> val; // 同上理 } if (root -> right) { tmp.push_back(root -> val); subsum += root -> val; pathSum(root -> right, ans, tmp, subsum, sum); tmp.pop_back(); // 保持tmp } } vector<vector<int> > pathSum(TreeNode *root, int sum) { vector<vector<int> > ans; vector<int> tmp; pathSum(root, ans, tmp, 0, sum); return ans; } };
标签:style blog http io ar color sp for on
原文地址:http://www.cnblogs.com/higerzhang/p/4132832.html