leecode 解题总结:113. Path Sum II
来源:互联网 发布:数据库教学视频哪个好 编辑:程序博客网 时间:2024/05/21 06:30
#include <iostream>#include <stdio.h>#include <vector>using namespace std;/*问题: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 1return[ [5,4,11,2], [5,8,4,5]]分析:这和之前的要求不一样,需要输出从根节点到叶节点的值,我们可以用一个数组存储结点的值。具体做法如下:存储当前结点的值到数组中,如果当前结点是叶子结点,计算数组中所有元素的和是否等于给定值,如果等于,就将数组存储到结果集中;否则,表明当前叶子结点所有值不符合,从数组中弹出当前叶子结点的值,关键:1 //注意result不能用引用,会改变另一条路径的值void dfs(TreeNode* root , int sum , vector<int> result , vector< vector<int> >& results)*/struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public://注意result不能用引用,会改变另一条路径的值void dfs(TreeNode* root , int sum , vector<int> result , vector< vector<int> >& results){//当前结点为空,肯定不可能,直接返回if(!root){return ;}result.push_back(root->val);sum -= root->val;//如果当前结点为叶子结点,计算结果if(NULL == root->left && NULL == root->right){//如果符合要求if(0 == sum){results.push_back(result);}//不符合要求,需要弹出当前结点对应的值else{result.pop_back();}}//如果当前结点的左孩子不空,递归处理if(root->left){dfs(root->left , sum , result , results);}if(root->right){dfs(root->right , sum , result , results);}} vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> results;vector<int> result;dfs(root , sum , result , results);return results; }};void print(vector<int>& result){if(result.empty()){cout << "no result" << endl;return;}int size = result.size();for(int i = 0 ; i < size ; i++){cout << result.at(i) << " " ;}cout << endl;}void process(){ vector<int> nums; int value; int num; Solution solution; vector<int> result; while(cin >> num ) { nums.clear(); for(int i = 0 ; i < num ; i++) { cin >> value; nums.push_back(value); } }}int main(int argc , char* argv[]){process();getchar();return 0;}
0 0
- leecode 解题总结:113. Path Sum II
- leecode 解题总结:64. Minimum Path Sum
- leecode 解题总结:112. Path Sum
- leecode 解题总结:40 Combination Sum II
- LeeCode No.113 Path Sum II
- [leetcode] 113. Path Sum II 解题报告
- [Leetcode] 113. Path Sum II 解题报告
- leecode 解题总结:71. Simplify Path
- leecode 解题总结:15 3Sum
- leecode 解题总结:16 3Sum Closest
- leecode 解题总结:18 4Sum
- leecode 解题总结:39. Combination Sum
- leecode 解题总结:303. Range Sum Query
- leecode 解题总结:307. Range Sum Query
- leecode 解题总结:45. Jump Game II
- leecode 解题总结:47. Permutations II
- leecode 解题总结:52. N-Queens II
- leecode 解题总结:59. Spiral Matrix II
- java基础知识(2)
- 单例模式--JAVA
- js打印页面指定内容
- ERROR 1130 (HY000): Host 'localhost' is not allowed to connect to this MySQL server
- jQuery学习篇(3)_jQuery 事件
- leecode 解题总结:113. Path Sum II
- 常见的几种RuntimeException
- log4j和logback冲突 mvn
- POJ 3507 Judging Olympia (格式控制)
- 宏碁4752G换CPU和显卡导热硅脂步骤
- 获取手机设备 信息
- 跟着高博学slam
- cygwin搭建C++开发环境
- android studio 倒入别人项目的技巧