路径总和 II—leetcode113
生活随笔
收集整理的這篇文章主要介紹了
路径总和 II—leetcode113
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一個二叉樹和一個目標和,找到所有從根節點到葉子節點路徑總和等于給定目標和的路徑。
說明:?葉子節點是指沒有子節點的節點。
示例:
給定如下二叉樹,以及目標和?sum = 22,
返回:
[[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:vector<vector<int>> pathSum(TreeNode* root, int sum) {vector<vector<int>> res;if(root == NULL) return res;vector<int> temp;findPath(root, sum, 0, temp, res);return res;}void findPath(TreeNode* root, int sum, int pathSum, vector<int> temp, vector<vector<int>> &res){if(root->left == NULL && root->right == NULL && root->val + pathSum == sum){temp.push_back(root->val);res.push_back(temp);return;}temp.push_back(root->val);if(root->left) findPath(root->left, sum, pathSum + root->val, temp, res);if(root->right) findPath(root->right, sum, pathSum + root->val, temp, res);} };?
總結
以上是生活随笔為你收集整理的路径总和 II—leetcode113的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 二叉树的后序遍历—leetcode145
- 下一篇: 翻转字符串里的单词—leetcode15