题目描述

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


 

依然是递归,一个关键点是把结果和当前路径与和存储为类的变量,减少了对结果集合和当前路径繁琐的合并与传递等操作。

 

/*
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> > re;
    vector<int> currentPath;
    int currentSum = 0;
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        if (root == NULL) return re;
        currentPath.push_back(root->val);
        currentSum += root->val;
        if (currentSum == expectNumber && root->left == NULL && root->right == NULL) {
            re.push_back(currentPath);
        } else {
            FindPath(root->left, expectNumber);
            FindPath(root->right, expectNumber);
        }
        currentPath.pop_back();
        currentSum -= root->val;
        return re;
    }
};

 

相关文章:

  • 2021-08-21
  • 2022-02-13
  • 2021-11-29
  • 2021-06-11
  • 2022-12-23
  • 2022-02-12
  • 2022-12-23
猜你喜欢
  • 2021-12-05
  • 2021-10-22
  • 2021-04-24
  • 2021-10-19
  • 2021-07-24
  • 2022-12-23
相关资源
相似解决方案