Leetcode-257. Binary Tree Paths
来源:互联网 发布:青少年行知实践园的题 编辑:程序博客网 时间:2024/06/05 02:03
Description:
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"]
解题思路:本题利用深度遍历解决,每次访问到叶子结点,开始打印路径。这里需要注意的是,每次递归返回后需要删除当前的叶子结点,防止路径重复打印。
Solution:class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result; //保存所有的路径信息
if(!root) return result;
string temp = to_string(root->val); //以字符串形式保存当前访问到的结点信息
DFS(root, result, temp);
return result;
}
void DFS(TreeNode* root, vector<string>& result, string temp)// 深度遍历
{
int index;
if(!root->left&&!root->right) //访问到叶子结点,表示一条完整的路径,存入vector
{
result.push_back(temp);
return;
}
if(root->left) //递归左子树
{
temp += "->" + to_string(root->left->val);
DFS(root->left, result, temp);
index = temp.rfind("->", temp.size()-1);//递归返回需要删除当前结点信息
temp.erase(index, temp.size() - index);
}
if(root->right) //递归右子树
{
temp += "->" + to_string(root->right->val);
DFS(root->right, result, temp);
index = temp.rfind("->", temp.size()-1);
temp.erase(index, temp.size() - index);
}
}
};
阅读全文
0 0
- [leetcode] 257. Binary Tree Paths
- 257. Binary Tree Paths LeetCode
- 【LeetCode】257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- LeetCode *** 257. Binary Tree Paths
- leetcode 257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- Leetcode 257. Binary Tree Paths
- LeetCode-257.Binary Tree Paths
- 【leetcode】257. Binary Tree Paths
- [Leetcode]257. Binary Tree Paths
- LeetCode - 257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- [leetcode] 257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- 257.[Leetcode]Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- leetcode 257. Binary Tree Paths
- python字符串与非字符串拼接三种方式
- MyBatis,动态传入表名,字段名的解决办法转载()
- 微信小程序--wx:openLocation的坑
- 数据库的数据的不可读,脏读,幻读和丢失更新
- Linux命令分析: chmod
- Leetcode-257. Binary Tree Paths
- Web应用架构的新趋势---前端和后端分离的一点想法
- 【重磅推荐】MySQL大表优化方案(最全面)
- ant和maven的区别
- avocado学习笔记
- TCP协议
- linux下用top命令查看cpu利用率超过100%
- iOS开发-轻松学会封装自定义视图view(自定义弹框封装详解)
- Android Studio(2.3.3)配置Kotlin笔记