剑指offer:二叉树中和为某一值的路径
二叉树中和为某一值的路径
http://www.nowcoder.com/questionTerminal/b736e784e3e34731af99065031301bca
1.二叉树的问题一般是递归解决
路径问题的话:1:定义一个全局的答案变量
2:定义每一轮的搜索路径path变量
2.递归函数中之间先判断结束条件,如没有左右儿子结点而且数字减到0;将这条路径加入到答案中去,如果不满足,则跳入到下一层中!递归函数可以是bool类型,也可以是void类型。
3.在一条path添加完后,记得还原现场,path.pop_back.
代码如下:
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } };*/ class Solution { public: vector<vector<int>> ans; vector<int> path; vector<vector<int> > FindPath(TreeNode* root,int sum) { dfs(root,sum); return ans; } void dfs(TreeNode* root,int sum){ if(!root) return ; path.push_back(root->val); sum-=root->val; if(!root->left && !root->right && !sum) ans.push_back(path); dfs(root->left,sum); dfs(root->right,sum); path.pop_back(); //恢复现场 } };