Leetcode--Path Sum II

来源:互联网 发布:河北大学网络教育平台 编辑:程序博客网 时间:2024/05/22 09:49

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

Hide Tags
 Tree Depth-first Search























思路:与Path Sum 类似,只是function函数多一个参数记录当前的路径

/** * 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>> res;    void function(TreeNode *root,int num,vector<int> v)    {        if(root==NULL)        {            if(num==0)                res.push_back(v);        }        else{            int temp=num-root->val;            vector<int> tmp(v);            tmp.push_back(root->val);            if(root->left==NULL&&root->right==NULL)                function(root->left,temp,tmp);            else if(root->left==NULL&&root->right!=NULL)                function(root->right,temp,tmp);            else if(root->left!=NULL&&root->right==NULL)                function(root->left,temp,tmp);            else{                function(root->left,temp,tmp);                function(root->right,temp,tmp);            }        }    }    vector<vector<int> > pathSum(TreeNode *root, int sum) {        if(root==NULL)            return res;        vector<int> v;        function(root,sum,v);        return res;    }};









0 0
原创粉丝点击