【剑指offer】题25:二叉树路径和为某一值

来源:互联网 发布:新西游记知乎 编辑:程序博客网 时间:2024/06/08 00:39

递归

class Solution {public:    vector<vector<int> > FindPath(TreeNode* root, int expectNumber) {        vector<vector<int>> result;        if (root == NULL)        {            return result;        }        stack<int> my_stack;        FindPath_Core(root, expectNumber,my_stack, result);        return result;    }    void FindPath_Core(TreeNode* root, int & sum,stack<int>& my_stack, vector<vector<int>>& result)    {        sum -= root->val;        my_stack.push(root->val);        if (root->left==NULL&&root->right==NULL&&sum ==0)        {            auto tmp = my_stack;            vector<int> vec;            while (!tmp.empty())            {                vec.insert(vec.begin(),tmp.top());                tmp.pop();            }            result.push_back(vec);        }        if (root->left!=NULL)        {            FindPath_Core(root->left, sum, my_stack, result);        }        if (root->right!=NULL)        {            FindPath_Core(root->right, sum, my_stack, result);        }        sum += root->val;        my_stack.pop();    }};