Leetcode 113. Path Sum II
来源:互联网 发布:淘宝优惠提醒app 编辑:程序博客网 时间:2024/06/08 12:32
Leetcode 113. Path Sum II
source url
题目描述
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]]
输入:树,目标和
输出:从根到叶满足目标和的路径
思路
深度有限搜索,同时维护一个根到当前节点路径,并且在叶子节点处进行判断;检查是否符合目标和,如果符合则将路径添加到输出结果中。此处,如果能确定树中节点值均为正数的话,可以通过剪枝操作减少运算量。
代码
/** * 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> > res; vector<vector<int> > pathSum(TreeNode* root, int sum) { if(root==NULL) return res; vector<int> emp; dfs(root,emp,sum); return res; } void dfs(TreeNode* root, vector<int> t, int sum){ if(root->left==NULL&&root->right==NULL){ if(root->val==sum){ t.push_back(root->val); res.push_back(t); return; } }else{ t.push_back(root->val); if(root->left!=NULL){ dfs(root->left,t,sum-root->val); } if(root->right!=NULL){ dfs(root->right,t,sum-root->val); } } }};
阅读全文
0 0
- LeetCode 113. Path Sum II
- [LeetCode]113.Path Sum II
- [Leetcode] 113. Path Sum II
- [leetcode] 113.Path Sum II
- [LeetCode]113. Path Sum II
- LeetCode: 113. Path Sum II
- leetcode 113. Path Sum II
- 113. Path Sum II LeetCode
- leetcode 113. Path Sum II
- LeetCode *** 113. Path Sum II
- Leetcode 113. Path Sum II
- LeetCode 113. Path Sum II
- LeetCode 113. Path Sum II
- LeetCode - 113. Path Sum II
- Leetcode 113. Path Sum II
- [LeetCode] 113. Path Sum II
- [leetcode] 113. Path Sum II
- [LeetCode] 113. Path Sum II
- 求1000以内素数平均值
- 原型模式prototype-发送邮件实例
- BAT批处理中选择分支后启动新窗口执行命令的示例
- Django Channels 实时在线用户列表
- WebRoot与WebContent区别
- Leetcode 113. Path Sum II
- 常用排序法(冒泡法,选择法)
- 给调皮的AssetBundle加上面向对象式加载调试管理
- 在Java中使用Lambda表达式统计词频
- @Autowired和@Resource的区别是什么?
- Java菜鸟第一天
- HCNA网络技术基础学习
- Mybatis关联、集合查询
- table View