113. Path Sum II

来源:互联网 发布:考勤机已删除数据恢复 编辑:程序博客网 时间:2024/05/16 04:27

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]]

Subscribe to see which companies asked this question

分析:

前序遍历求节点和。运行时间很慢,得优化

/**
 * 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) {
        vector<vector<int>> v2;
        vector<int> v1;
        if(root==NULL) return v2;
        return travel(root,0,sum,v1,v2);
    }
    vector<vector<int>> travel(TreeNode* root, int temp,int sum,vector<int> v1,vector<vector<int>>&v2)
    {
        if(root->left==NULL && root->right==NULL)
        {

            if(temp+root->val==sum) {v1.push_back(root->val);v2.push_back(v1);}
            return v2;
        }
        v1.push_back(root->val);
        temp+=root->val;
        if(root->left){travel(root->left,temp,sum,v1,v2);}
        if(root->right){travel(root->right,temp,sum,v1,v2);}
        return v2;
    }
};

0 0
原创粉丝点击