113. Path Sum II
来源:互联网 发布:考勤机已删除数据恢复 编辑:程序博客网 时间:2024/05/16 04:27
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]]
Subscribe to see which companies asked this question
分析:
前序遍历求节点和。运行时间很慢,得优化
/**
* 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>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> v2;
vector<int> v1;
if(root==NULL) return v2;
return travel(root,0,sum,v1,v2);
}
vector<vector<int>> travel(TreeNode* root, int temp,int sum,vector<int> v1,vector<vector<int>>&v2)
{
if(root->left==NULL && root->right==NULL)
{
if(temp+root->val==sum) {v1.push_back(root->val);v2.push_back(v1);}
return v2;
}
v1.push_back(root->val);
temp+=root->val;
if(root->left){travel(root->left,temp,sum,v1,v2);}
if(root->right){travel(root->right,temp,sum,v1,v2);}
return v2;
}
};
- 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
- objective-c C类型数组
- Xilinx SRIO ID
- Java设计模式之“抽象工厂模式“
- Info.plist和pch文件的作用,UIApplication,iOS程序的启动过程,AppDelegate 方法解释,UIWindow,生命周期方法
- 推荐一个C#调用winapi的帮助网站
- 113. Path Sum II
- 系统缓冲区、内核缓冲区、IO库操作本身的缓冲区 之间联系
- 利用ip helper-address配置DHCP
- 欢迎使用CSDN-markdown编辑器
- 如何在 Git 里撤销(几乎)任何操作
- Apache Cordova for ios环境配置
- 欢迎使用CSDN-markdown编辑器
- Ubuntu14.04后台进程Nohup
- TSC条码打印机亮红灯解决办法!