leetcode之Path Sum II

来源:互联网 发布:js 数组输出到html 编辑:程序博客网 时间:2024/05/15 19:08

题目大意:

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]]
意思就是:

紧跟Path Sum,只是需要输出各种可能的情况.

/** * Definition for binary tree * 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) {        result.clear();        if(!root){return result;}vector<int> a;dfsTravel(root, sum, a);return result;         }    void dfsTravel(TreeNode* node, int rest, vector<int> a){rest = rest - node->val;a.push_back(node->val);if(rest == 0 && !node->left && !node->right){result.push_back(a);return;}if(node->left){dfsTravel(node->left, rest, a);}if(node->right){dfsTravel(node->right, rest, a);}}private:vector< vector<int> > result;};


0 0
原创粉丝点击