剑指offer 二叉树中和为某一值的路径

  • 题目描述

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。


  • 递归解法
  1. class Solution {
  2. public:
  3. vector<vector<int>> ret;
  4. vector<int> t;
  5. vector<vector<int> > FindPath(TreeNode* root, int expectNumber) {
  6. TreeNode* p = root;
  7. stack<int> s;
  8. if (root != NULL)
  9. dfs(root, expectNumber);
  10. return ret;
  11. }
  12. void dfs(TreeNode* root, int e){
  13. t.push_back(root->val);
  14. if (root->left == NULL && root->right == NULL && e-root->val==0)
  15. ret.push_back(t);
  16. else{
  17. if (root->left)
  18. dfs(root->left, e-root->val);
  19. if (root->right)
  20. dfs(root->right, e-root->val);
  21. }
  22. t.pop_back();
  23. }
  24. };
  • 非递归解法

这个非递归还真是有点不太好写。。

  1. class Solution {
  2. public:
  3. vector<vector<int>> res;
  4. vector<vector<int> > FindPath(TreeNode* root, int expectNumber) {
  5. TreeNode* p = root;
  6. if (root == NULL)
  7. return res;
  8. stack<TreeNode*> s;
  9. s.push(root);
  10. int sum = 0;//当前和
  11. vector<int> curPath;
  12. TreeNode *cur = root;
  13. TreeNode *last = NULL;
  14. while (!s.empty()){
  15. if (cur == NULL){
  16. TreeNode* t = s.top();
  17. if (t->right != NULL && t->right != last)
  18. cur = t->right;//转向未遍历过的右子树
  19. else{
  20. last = t;//保存上一个已遍历地结点
  21. s.pop();
  22. curPath.pop_back();//从当前路径删除
  23. sum -= t->val;
  24. }
  25. }
  26. else{
  27. s.push(cur);
  28. sum += cur->val;
  29. curPath.push_back(cur->val);
  30. if (cur->left == NULL&&cur->right == NULL&&sum == expectNumber)
  31. res.push_back(curPath);
  32. cur = cur->left;//先序遍历,左子树先于右子树
  33. }
  34. }
  35. return res;
  36. }
  37. };
弹钢琴的猫 /
Published under (CC) BY-NC-SA in categories 算法  tagged with 剑指offer  Tree