LeetCode OJ - Path Sum II

来源:互联网 发布:如何带领团队 知乎 编辑:程序博客网 时间:2024/06/02 06:13

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记录路劲,一次提交AC

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {    vector<vector<int> > ret;    int SUM;public:    vector<vector<int> > pathSum(TreeNode *root, int sum) {        if(!root) return ret;        vector<int> item;        SUM = sum;        DFS(root, item);        return ret;    }        void DFS(TreeNode *root, vector<int> item) {        item.push_back(root->val);        if(!root->left && !root->right) {            int tmp = 0;            for(int i = 0; i < item.size(); i++)                tmp += item[i];            if(tmp == SUM) {                ret.push_back(item);            }            return ;        }        if(root->left) DFS(root->left, item);        if(root->right) DFS(root->right, item);            }};




0 0
原创粉丝点击