LeetCode 257. 二叉树的所有路径(DFS)
发布日期:2021-07-01 03:14:08 浏览次数:2 分类:技术文章

本文共 813 字,大约阅读时间需要 2 分钟。

文章目录

1. 题目

给定一个二叉树,返回所有从根节点到叶子节点的路径。

说明: 叶子节点是指没有子节点的节点。

示例:输入:   1 /   \2     3 \  5输出: ["1->2->5", "1->3"]解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/binary-tree-paths
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. DFS解题

在这里插入图片描述

class Solution {
public: vector
binaryTreePaths(TreeNode* root) {
string path; vector
ans; walk(root, path, ans); return ans; } void walk(TreeNode* root, string path, vector
& ans) {
if(root == NULL) return; walk(root->left, path+to_string(root->val)+"->", ans); walk(root->right, path+to_string(root->val)+"->", ans); if(!root->left && !root->right) {
path += to_string(root->val); ans.push_back(path); } }};

转载地址:https://michael.blog.csdn.net/article/details/100565918 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode 814. 二叉树剪枝(递归)
下一篇:LeetCode 535. TinyURL 的加密与解密(哈希)

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年04月14日 16时54分23秒