[leetcode] 113.Path Sum II

来源:互联网 发布:matlab求矩阵的秩 编辑:程序博客网 时间:2024/05/16 01:33

题目:
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]
]
题意:
找出所有的从根节点到叶子节点和为给定值的路径,保存路径上的值并返回。
思路:
参照112题,采用回溯的方法。
以上。
代码如下:

/** * 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>> result;        if(root == NULL)return result;        vector<int> temp;        PathSum(root,sum,temp,result);        return result;    }    void PathSum(TreeNode* root, int sum, vector<int>& temp,vector<vector<int>> & result) {        if(root->left == NULL && root->right == NULL){            if(root->val == sum){                temp.push_back(root->val);                result.push_back(temp);                temp.pop_back();            }            return;        }        if(root->left != NULL){            temp.push_back(root->val);            PathSum(root->left,sum - root->val,temp,result);            temp.pop_back();        }         if(root->right != NULL){            temp.push_back(root->val);            PathSum(root->right,sum - root->val,temp,result);            temp.pop_back();        }     }};
0 0
原创粉丝点击