Path Sum II

来源:互联网 发布:g71格式编程 编辑:程序博客网 时间:2024/06/05 14:55

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]

]

ret

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    void pathArray(TreeNode *root,int sum,vector<vector<int> > &vec,vector<int> subVec)    {        if(root){            sum-=root->val;            subVec.push_back(root->val);        }else{            return;        }        if(root->left==nullptr&&root->right==nullptr){            if(sum==0){                vec.push_back(subVec);            }        }        pathArray(root->left,sum,vec,subVec);        pathArray(root->right,sum,vec,subVec);    }    vector<vector<int> > pathSum(TreeNode *root, int sum) {        vector<vector<int> > vec;        vector<int> subVec;        pathArray(root,sum,vec,subVec);        return vec;    }};


0 0