113. Path Sum II
来源:互联网 发布:java栈内存溢出 编辑:程序博客网 时间:2024/06/10 15:01
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]
]
解答:其实就是深度优先搜索,重点在于解决函数接口问题,传入一个root节点,一个到目前为止的所加的值,一个目标值,一个到目前为止的暂时所存的vector
class Solution {public: vector<vector<int>> result; void path(TreeNode* root,int now,int target,vector<int> res) { if(root==NULL) return ; now+=root->val; res.push_back(root->val); if(root->left) path(root->left,now,target,res); if(root->right) path(root->right,now,target,res); if(now==target&&(root->left==NULL)&&(root->right==NULL)) result.push_back(res); } vector<vector<int>> pathSum(TreeNode* root, int sum) { if(root==NULL) return result; vector<int> res; path(root,0,sum,res); return result; }};
二刷时是这么做的,更符合我的习惯
/** * 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>> result; vector<vector<int>> pathSum(TreeNode* root, int sum) { dfs(root,{},0,sum); return result; } void dfs(TreeNode* root,vector<int> path,int temp,int target) { if(!root) return; temp=temp+root->val; path.push_back(root->val); if((temp==target)&&(root->left==NULL&&root->right==NULL)) { result.push_back(path); return ; } dfs(root->left,path,temp,target); dfs(root->right,path,temp,target); }};
0 0
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- redis做缓存的demo
- HTML + CSS短标题(二,三,四文字长度)两端对齐的方式
- Android 中ArrayAdapter,SimpleAdapter,BaseAdapter三种适配器的使用
- 线性布局LinearLayout常用属性
- 递归
- 113. Path Sum II
- Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/sc
- virtualbox CentOs设置共享文件夹
- RESTful登录设计(基于Spring及Redis的Token鉴权)
- python 知识点(四)函数
- shader01-基础练习
- redis使用详细教程
- 洛谷 P1108 低价购买
- 使用fscok实现异步调用PHP