leetcode_c++:树: Path SumII(113)

来源:互联网 发布:谁人知歌词 编辑:程序博客网 时间:2024/05/18 00:44

Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.

For example:
Given the below binary tree and sum = 22,

              5             / \            4   8           /   / \          11  13  4         /  \    / \        7    2  5   1

return

[   [5,4,11,2],   [5,8,4,5]]

算法

dfs
O(n)


class Solution {private:    void dfs(TreeNode *root, int rest, vector<int> &path,            vector<vector<int> > &res) {        if (root == NULL)            return;        path.push_back(root->val);        rest -= root->val;        if (root->left == NULL && root->right == NULL) {            if (rest == 0)                res.push_back(path);        } else {            if (root->left)                dfs(root->left, rest, path, res);            if (root->right)                dfs(root->right, rest, path, res);        }        path.pop_back();    }public:    vector<vector<int> > pathSum(TreeNode *root, int sum) {        vector<vector<int> > res;        vector<int> path;        dfs(root, sum, path, res);        return res;    }};
0 0
原创粉丝点击