Path Sum II(leetcode)
来源:互联网 发布:json 数据解析 乱码 编辑:程序博客网 时间:2024/06/03 13:58
题目:
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]]
题目来源:https://oj.leetcode.com/problems/path-sum-ii/
解题思路:用先序遍历进行深搜
#include<iostream>#include<vector>using namespace std;struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};//先序遍历void dfs(TreeNode *root,int temp,vector<int> &result,vector<vector<int> > &results,int sum){if(root==NULL)return ;temp+=root->val;result.push_back(root->val);if(root->left==NULL && root->right==NULL){if(temp==sum){results.push_back(result);result.pop_back();return ;}}dfs(root->left,temp,result,results,sum);dfs(root->right,temp,result,results,sum);result.pop_back();}vector<vector<int> > pathSum(TreeNode *root, int sum){vector<vector<int> >results;if(root==NULL)return results;vector<int> result;dfs(root,0,result,results,sum);return results;}int main(){TreeNode *root=new TreeNode(-2);//root->left=new TreeNode(2);root->right=new TreeNode(-3);vector<vector<int> > results=pathSum(root,-5);system("pause");return 0;}
0 0
- LeetCode: Path Sum II
- LeetCode Path Sum II
- [Leetcode] Path Sum II
- LeetCode: Path Sum II
- [LeetCode] Path Sum II
- 【leetcode】Path Sum II
- [LeetCode]Path Sum II
- [Leetcode]Path Sum II
- [leetcode]Path Sum II
- Leetcode: Path Sum II
- LeetCode-Path Sum II
- [leetcode] Path Sum II
- LeetCode - Path Sum II
- [LeetCode] Path Sum II
- Leetcode Path Sum II
- LeetCode | Path Sum II
- 【leetcode】Path Sum II
- [LeetCode] Path Sum II
- HDU 5090 Game with Pearls(贪心)
- http错误码大全
- Mybatis foreach 批量操作
- css效果
- 第十一周上机项目六(3)素数
- Path Sum II(leetcode)
- http://write.blog.csdn.net/postedit/40896053
- Oracle 控制文件(controlfile)
- 从容网掀起互联网金融新革命
- GestureDetector.OnGestureListener 详解
- 使用WinSCP软件在windows和Linux中进行文件传输
- lua实现的A星(a star)算法
- UVA - 10041 Vito's Family 求中位数
- Breakout detection in the wild