剑指offer题解C++【24】二叉树中和为某一值的路径

来源:互联网 发布:淘宝卖家资金保护中 编辑:程序博客网 时间:2024/06/09 17:30

题目描述

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

解题思路

按照先序遍历将结点加入路径,如果当前结点是叶子结点则判断当前路径和是否为目标数,若满足条件,则把当前路径保存下来,并弹出结点;每一次递归返回父结点时,也回退一个结点。

代码

/*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> > FindPath(TreeNode* root,int expectNumber) {        vector<vector<int> > res;        vector<int> path;        if (root == nullptr)            return res;        Search(root, expectNumber, res, path);        return res;    }    void Search(TreeNode * root, int expectNumber, vector<vector<int> > & res, vector<int> & path) {        if (root->left == nullptr && root->right == nullptr) {            if (root->val == expectNumber) {                path.push_back(root->val);                res.push_back(path);                path.pop_back();            }            return;        }        path.push_back(root->val);        if (root->left)            Search(root->left, expectNumber - root->val, res, path);        if (root->right)            Search(root->right, expectNumber - root->val, res, path);        path.pop_back();    }};
原创粉丝点击