leetcode 每日一题 257. Binary Tree Paths
2016-03-29 12:47
357 查看
给出二叉树,求所有从根到叶子节点的路径并打印
这道题可以用递归解(DFS),但是对递归理解的还是不够,并且判断条件的时候太大意了 一直RE,烦得很
后来经臭臭指点找到了原因。
在上面的程序中,由于else中没有判断左右孩子是否为空的情况,因此需要加一个head==NULL作为终止条件,这个是不能加到主函数的
但如果判断了,则可以在主函数中判断root
代码如下 https://leetcode.com/discuss/93742/c-non-recursive-version-and-recursive-version
另外就是to_string函数的使用,之前没怎么接触过~
此题过段时间应再刷一遍····很多很多需要避免的漏洞
这道题可以用递归解(DFS),但是对递归理解的还是不够,并且判断条件的时候太大意了 一直RE,烦得很
后来经臭臭指点找到了原因。
vector<string> binaryTreePaths(TreeNode* root) { TreeNode* head=root; //记得赋值啊! vector<string> res; string str=""; //if(head==NULL) return res; printPath(head,res,str); return res; } void printPath(TreeNode* head,vector<string> &res,string str){ if(head==NULL) return; //停止条件 str+=to_string(head->val); if(head->left==NULL&&head->right==NULL){ res.push_back(str); return; //停止条件,也就是停止到上一个递归 } else{ str+="->"; printPath(head->left,res,str); //分开考虑则不需要判断head printPath(head->right,res,str); } }
在上面的程序中,由于else中没有判断左右孩子是否为空的情况,因此需要加一个head==NULL作为终止条件,这个是不能加到主函数的
但如果判断了,则可以在主函数中判断root
代码如下 https://leetcode.com/discuss/93742/c-non-recursive-version-and-recursive-version
vector<string> binaryTreePaths(TreeNode* root) { vector<string> res; if (root == NULL) return res; dfs(root, to_string(root->val), res); return res; } void dfs(TreeNode* root, string path, vector<string>& res) { if (root->left == NULL && root->right == NULL) { res.push_back(path); } if (root->left != NULL) dfs(root->left, path + "->" + to_string(root->left->val), res); if (root->right != NULL) dfs(root->right, path + "->" + to_string(root->right->val), res); }
另外就是to_string函数的使用,之前没怎么接触过~
此题过段时间应再刷一遍····很多很多需要避免的漏洞
相关文章推荐
- Android中的回调
- zookeeper-3.4.8单机与主从安装与配置
- lintcode-medium-Longest Palindromic Substring
- js 头像上传(图片截取) 插件 全屏高清版 源码
- hadoop从安装到布署
- 第一章 Activity的生命周期和启动模式
- 判别分析基础
- sqlite3之sqlite3_busy_handler使用详解
- 签到题2016.3.29
- androidStudio中出现finished with non-zero exit value 2 或者 finished with non-zero exit value 1
- 生活不止眼前的苟且,还有诗和远方。
- 十大类库
- codeforces 658C C. Bear and Forgotten Tree 3(tree+乱搞)
- android基础学习之动画基础
- Cocos2dx动作篇
- op cache config
- cf23C Oranges and Apples (贪心_好题)
- IOS开发-UI学习-使用代码创建button
- mysqll底层分享(一):MySQL索引背后的数据结构及算法原理
- PL/SQL developer连接oracle