112. Path Sum
来源:互联网 发布:表格中数据单位转换 编辑:程序博客网 时间:2024/05/16 08:47
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:Given the below binary tree and
sum = 22
,5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
solution:
/** * 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: bool hasPathSum(TreeNode* root, int sum) { vector<int> ps; int flag; traverse(root, sum, flag, ps); return flag==1; } void traverse(TreeNode* root, int sum, int &flag, vector<int> ps){ if(!root) return; if(ps.size()==0) ps.push_back(0); ps[ps.size()-1] += root->val; if(!root->left&&!root->right) { if(ps[ps.size()-1]==sum) {flag=1; return;} else return; } if(root->left&&!root->right) traverse(root->left, sum, flag, ps); if(root->right&&!root->left) traverse(root->right, sum, flag, ps); if(root->left&&root->right){ int tmp = ps[ps.size()-1]; traverse(root->left, sum, flag, ps); ps.push_back(tmp); traverse(root->right, sum, flag, ps); } }};心得:思路比较简单,运行时间较长,搜了一下别人的方法 http://blog.csdn.net/booirror/article/details/42680111 这个方法很好,我自己一直纠结于加确没有考虑减,导致代码冗长
运行时间:慢
0 0
- 112. Path Sum && 113. Path Sum II
- 112. Path Sum&113. Path Sum II
- 112.Path Sum
- LeetCode 112. Path Sum
- [LeetCode]112.Path Sum
- 【LeetCode】112.Path Sum
- [Leetcode] 112. Path Sum
- [leetcode] 112.Path Sum
- 112.Path Sum
- 112. Path Sum
- 112. Path Sum
- 112. Path Sum
- 112. Path Sum
- 112. Path Sum LeetCode
- 112. Path Sum
- 112. Path Sum
- 112. Path Sum
- 112. Path Sum
- [转载]树链剖分
- oatdump使用命令
- Wireshark 抓包工具http://blog.jobbole.com/70907/
- addr2line命令
- c与c++区别
- 112. Path Sum
- 删除多余的被占用的串口
- Xcode集成POD教程
- 使用AdMob实现广告统一
- String.format方法,Java常用类库——Formatter
- 安卓 Volley+OkHttp3+Gson(Jackson)开源库的封装过程
- Keil-MDK编译完成后代码大小
- POJ 2096
- textfield监听删除按键 包括没有输入文字时(ios8 也可以使用)