LintCode 376: Binary Tree Path Sum
来源:互联网 发布:淘宝和易趣的相同点 编辑:程序博客网 时间:2024/06/02 02:28
Description:
Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target.
Note:
1.a valid path的定义是 from root node to any of the leaf nodes.所以当满足target条件时还要判断最后一个结点的左右子树是否为空(啊每次都不认真审题要注意啊)
2.注意函数getSum中的sum和path是不加引用,而result是加引用的,因为sum和path在递归中是不共享的,每次更新只作为参数传递下去,而result需要在递归中共享结果。
Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target.
Note:
1.a valid path的定义是 from root node to any of the leaf nodes.所以当满足target条件时还要判断最后一个结点的左右子树是否为空(啊每次都不认真审题要注意啊)
2.注意函数getSum中的sum和path是不加引用,而result是加引用的,因为sum和path在递归中是不共享的,每次更新只作为参数传递下去,而result需要在递归中共享结果。
Code:
class Solution {void getSum(TreeNode* root, int target, int sum, vector<int> path, vector<vector<int>>& result) {if (!root)return;if (root->val + sum == target && !root->left && !root->right) {path.push_back(root->val);result.push_back(path);return;}sum += root->val;path.push_back(root->val);getSum(root->left, target, sum, path, result);getSum(root->right, target, sum, path, result);return;}public:/*** @param root the root of binary tree* @param target an integer* @return all valid paths*/vector<vector<int>> binaryTreePathSum(TreeNode *root, int target) {// Write your code herevector<vector<int>> result;vector<int> path;int sum = 0;getSum(root, target, sum, path,result);return result;}};
阅读全文
0 0
- LintCode 376 Binary Tree Path sum
- LintCode 376: Binary Tree Path Sum
- lintcode-376- Binary Tree Path Sum
- lintcode:Binary Tree Maximum Path Sum
- *[Lintcode]Binary Tree Maximum Path Sum
- [lintcode] Binary Tree Maximum Path Sum II
- Binary Tree Maximum Path Sum ---lintcode
- 20150708 lintcode 总结 Binary Tree Maximum Path Sum Show result *****
- [LintCode] 二叉树的路径之和 Binary Tree Path Sum
- Binary Tree Path Sum
- Binary Tree Path Sum
- Binary Tree Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Max Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- OPENCV图像直方图显示(代码)
- POJ2118-Firepersons
- Deepin Linux 安装JDK
- Resource Manager HA配置
- javaee学习日记之java基础之I/O流
- LintCode 376: Binary Tree Path Sum
- ThinkPHP5.0 控制器继承基类和自定义类
- Android存在的三种活动启动模式
- Kali 安装 Oracle jdk
- SSM框架项目中的bug汇总
- MySQL性能优化的最佳20+条经验
- Flask邮箱认证以及头像
- 关于使用bootstrap创建导航栏的一些学习心得(dropdown二级菜单)
- 【17/8】ui复习之togglebutton