leetcode 113. 路径总和 II(Path Sum II)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 113. 路径总和 II(Path Sum II)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
- 題目描述:
- 示例:
- 解法:
題目描述:
給定一個二叉樹和一個目標和,找到所有從根節點到葉子節點路徑總和等于給定目標和的路徑。
說明: 葉子節點是指沒有子節點的節點。
示例:
給定如下二叉樹,以及目標和 sum = 22,
5/ \4 8/ / \11 13 4/ \ / \7 2 5 1返回:
[[5,4,11,2],[5,8,4,5] ]解法:
/*** 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:void pathSum(TreeNode* root, int sum, int cur, vector<vector<int>>& res, vector<int>& path){if(root == NULL){return;}else{path.push_back(root->val);cur += root->val;if(cur == sum && root->left == NULL && root->right == NULL){res.push_back(path);}if(root->left){pathSum(root->left, sum, cur, res, path);}if(root->right){pathSum(root->right, sum, cur, res, path);}path.pop_back();}}vector<vector<int>> pathSum(TreeNode* root, int sum) {vector<vector<int>> res;vector<int> path;int cur = 0;pathSum(root, sum, cur, res, path);return res;} };轉載于:https://www.cnblogs.com/zhanzq/p/10785359.html
總結
以上是生活随笔為你收集整理的leetcode 113. 路径总和 II(Path Sum II)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Oracle Sql 胡乱记
- 下一篇: HDU - 3247 Resource