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

来源:互联网 发布:淘宝图片空间 编辑:程序博客网 时间:2024/05/16 05:10

题目描述

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

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector<vector<int> > pathSum(TreeNode* root, int sum) {        if (root == NULL){            return res;        }        vector<int> path;        helper(root, sum, path, 0);        return res;    }private:    void helper(TreeNode* root, int sum, vector<int>& path, int cur){        cur += root->val;        path.push_back(root->val);        if (root->left == NULL&&root->right == NULL){            if (cur == sum){                res.push_back(path);                //return;//不能要,后面要pop_back            }        }        if (root->left){            helper(root->left, sum, path, cur);        }        if (root->right){            helper(root->right, sum, path, cur);        }        path.pop_back();    }    vector<vector<int> >res;};
0 0
原创粉丝点击