Binary Tree Paths
来源:互联网 发布:百度云域名查询 编辑:程序博客网 时间:2024/04/30 13:47
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
[“1->2->5”, “1->3”]
第一个错误版本class Solution {public: vector<string> binaryTreePaths(TreeNode* root) { if(!root) return{}; vector<string> v; string s(""); binaryTreePaths(v,s,root); return v; } void binaryTreePaths(vector<string> &v,string s,TreeNode *root){ if(!root) return; string s1=root->val+""; if(s!="") s1=s+"->"+s1; if(!root->right||!root->left) v.push_back(s1); if(root->left) binaryTreePaths(v,s1,root->left); if(root->right) binaryTreePaths(v,s1,root->right); }};
这里错误原因在于对树的路径没有理解透彻,比如
1
/ \
2 3
\
5
正确的路径应该是如下:
[“1->2->5”, “1->3”]
而按照我之前的思路,路径就变成了
[“1->2”,”1->2->5”, “1->3”,]
路径是根到叶子的路径。而叶子是指既没有左孩子也没有右孩子,所以节点”2“不是叶子,所以”1->2”不是路径
正确的答案
class Solution {public: vector<string> binaryTreePaths(TreeNode* root) { if(!root) return{}; vector<string> v; // string s(""); binaryTreePaths(v,to_string(root->val),root); return v; } void binaryTreePaths(vector<string> &v,string s,TreeNode *root){ if(!root) return; // string s1=root->val+""; // if(s!="") s1=s+"->"+s1; if(!root->right&&!root->left) {v.push_back(s);return;} if(root->left) binaryTreePaths(v,s+"->"+to_string(root->left->val),root->left); if(root->right) binaryTreePaths(v,s+"->"+to_string(root->right->val),root->right); }};
int转化为string的两种方法:
1.string s=root->val+””
2.to_string(root->val)
0 0
- Binary Tree Paths
- Leetcode: Binary Tree Paths
- [LeetCode] Binary Tree Paths
- [Leetcode]Binary Tree Paths
- leetcode:Binary Tree Paths
- Binary Tree Paths
- [leetcode] Binary Tree Paths
- 257 Binary Tree Paths
- Binary Tree Paths
- [LeetCode257] Binary Tree Paths
- Binary Tree Paths
- Binary Tree Paths
- Leetcode: Binary Tree Paths
- LeetCode:Binary Tree Paths
- leetcode Binary Tree Paths
- leetcode Binary Tree Paths
- LeetCode:Binary Tree Paths
- Binary Tree Paths
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
- 搬家
- 简单谈谈对C++设计模式的理解
- MySQL基本操作
- K8S对node添加label,并根据label筛选节点
- Binary Tree Paths
- Android中画边框线,EditText四周边框线
- 代码GC测试
- git
- [http] HTTP Request Header 请求头
- Windows8下JDK8环境变量 jdk java环境变量
- leetcode题解-380. Insert Delete GetRandom O(1)
- 17.03.01 流程控制
- 基于记忆(Memory-Based)与基于模型(Model-Based)的辨析