[剑指offer] 24. 二叉树中和为某一值的路径

题目描述

输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

思路:
比较经典的利用记忆搜索的题目,题目提到要遍历到结尾,于是合法路径为:
加上该结点的值后等于目标值 同时 是叶子结点
注意在深度搜索后,需要恢复搜索前状态,来达到记忆化DFS效果。
class Solution
{
public:
  vector<vector<int>> res;
  vector<int> temp;
  vector<vector<int>> FindPath(TreeNode *root, int expectNumber)
  {
    if(root)
      dfs(root,expectNumber);
    return res;
  }
  void dfs(TreeNode *root, int leftNumber)
  {
    temp.push_back(root->val);
    if (leftNumber == root->val && root->left == NULL && root->right == NULL)
    {
      res.push_back(temp);
    }
    else
    {
      if (root->left)
        FindPath(root->left, leftNumber - root->val);
      if (root->right)
        FindPath(root->right, leftNumber - root->val);
    }
    temp.pop_back();
  }
};