LeetCode算法题-Binary Tree Paths(Java实现-3种解法)

全志F1C100S/F1C200S学习笔记(1)——基础简介及资料 资料: 荔枝派资料下载站 荔枝派github 荔枝派中文论坛 荔枝派DIY-github资料 荔枝派Nano 全流程指南 芒果派 坑网 阅读详情

这是悦乐书的第199次更新,第206篇原创

01 看题和准备

今天介绍的是LeetCode算法题中Easy级别的第62题(顺位题号是257)。给定二叉树,返回所有根到叶路径。例如:

输入:

  1
 / \
2   3
 \
  5

输出:[“1-> 2-> 5”,“1-> 3”]

说明:所有根到叶路径是:1-> 2-> 5, 1-> 3

注意:叶子是没有子节点的节点。

本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。

02 第一种解法

特殊情况:当根节点为null的时候,直接返回空数组。

正常情况:深度遍历,从根节点开始,依次从左节点开始,一直往左节点遍历进去,直到遇到叶子节点,此时就构成一条完整的路径,而其相邻的右叶子结点,以及从根节点开始的右节点,这些都是一条完整的路径。

public List<String> binaryTreePaths(TreeNode root) {
    List<String> list = new ArrayList<String>();
    if (root == null) {
        return list;
    }
    helperFun(root, list, "");
    return list;
}

public void helperFun(TreeNode root, List<String> list, String path) {
    if (root.left != null) {
        helperFun(root.left, list, path + root.val + "->");
    }
    if (root.right != null) {
        helperFun(root.right, list, path + root.val + "->");
    }
    if (root.left == null && root.right == null) {
        list.add(path + root.val);
    }
}

03 第二种解法

此解法也是利用递归,递归虽然写在方法内部了,但是思路和上面第一种解法的递归是一样的。

public List<String> binaryTreePaths2(TreeNode root) {
    List<String> list = new ArrayList<String>();
    if (root == null) {
        return list;
    }
    if (root.left == null && root.right == null) {
        list.add(root.val+"");
        return list;
    }
    for (String path : binaryTreePaths(root.left)) {
        list.add(root.val+"->"+path);
    }
    for (String path : binaryTreePaths(root.right)) {
        list.add(root.val+"->"+path);
    }
    return list;
}

04 第三种解法

使用迭代的方法,借助两个栈,一个存储节点信息,一个存储路径信息。

public List<String> binaryTreePaths3(TreeNode root) {
    List<String> list = new ArrayList<String>();
    Stack<TreeNode> sNode = new Stack<TreeNode>();
    Stack<String> sStr = new Stack<String>();
    if (root == null){
        return list;
    }
    sNode.push(root);
    sStr.push("");
    while (!sNode.isEmpty()) {
        TreeNode curNode = sNode.pop();
        String curStr = sStr.pop();
        if (curNode.left == null && curNode.right == null) {
            list.add(curStr + curNode.val);
        }
        if (curNode.left != null) {
            sNode.push(curNode.left);
            sStr.push(curStr + curNode.val + "->");
        }
        if (curNode.right != null) {
            sNode.push(curNode.right);
            sStr.push(curStr + curNode.val + "->");
        }
    }
    return list;
}

05 小结

算法专题目前已连续日更超过一个月,算法题文章62+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

【ATC/DTC方法第一期】经典平均/昼夜温度周期ATC/DTC方法介绍(含Python代码实现) 阅读详情

相关推荐

codesys工程ST语言学习笔记(二)写文件操作与添加库方法

ST语言文件读写功能 由于实验中需要大量的数据,文件读写比较方便,但是网上的文件读写的程序很多都用不了,小编将自己的工程发布出来

sf9090的博客 1万+

[leetcode-257]Binary Tree Paths(java)

问题描述: 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”]分析:使用递归的思想,且递归到叶节点时终止,即

中华胡杨的专栏 1035

Yersinia:layer 2攻击框架!全参数详细教程!Kali Linux教程!

Yersinia是一个专为执行二层网络攻击设计的框架,利用多种网络协议的弱点进行渗透测试和网络分析。它支持针对生成树协议(STP)、思科发现协议(CDP)、动态中继协议(DTP)、动态主机配置协议(DHCP)、热备用路由器协议(HSRP)、802.1q、802.1x、交换机间链路协议(ISL)和VLAN中继协议(VTP)的攻击。这些攻击可能导致网络中的拒绝服务(DoS)或为更复杂的攻击创造条件。Yersinia对渗透测试人员和网络管理员非常有用,但使用时需谨慎,以免造成网络不稳定。

qq_24305079的博客 2291

Leetcode257:二叉树的所有路径

public List<String> binaryTreePaths(TreeNode root) { List<String> res = new ArrayList<>(); if (root == null) { return res; } if (root.left == null && root.right...

很好的坏人 179

stackelberg博弈_博弈论、多智能体、强化学习(随便记点东西)

多智能体应用场景:已实现:游戏AI。正在努力:UAV,物资运输,快递分发,交通系统。未来:社会学,预测群体行为,城市区域合作,国际关系。博弈论基本定义:玩家集合: 策略集合: 收益函数: 囚徒困境:两智能体矩阵博弈坦白抵赖坦白1,13,0抵赖0,32,2占优策略与最佳应对:上表中两者均具有占优策略,即无论如何都应该选坦白。那么构造下表。坦白抵赖坦白1,13,0抵赖0,12,2对于玩家一来说,坦白...

weixin_39611722的博客 3008

IPMI的SOL (Serial Over LAN) 和 UART

UART全名是Universal Asynchronous Receiver/Transmitter(通用異步接收/发送器),它是一个常用的異步串行传输协议。透过UART传输前,接收方须要先知道传输方的鲍率(Baud rate):单位时间内,讯号状态变化的次数。例如 115200 bps,表示每秒会传送115200个bits--> 因此读取率就是 1/115200=8.6微秒读取一次讯号。封包内的资料长度:通常是 8bits。

yeiris的博客 1万+

Leetcode:257. Binary Tree Paths(JAVA)

【问题描述】 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"

莫名的程序猿 532

Windows C语言编程:Beep API实现蜂鸣器原理与实战

如果你在 Windows 上写过 C 语言程序,想给程序加个简单的提示音,第一个想到的可能是 printf("\a") 。这个转义字符确实能在某些终端里发出“嘀”的一声,但它太原始、太不可控了,而且很多时候根本没声音。那么,有没有一种更“Windows”、更可控、更专业的方法来让你的程序“说话”呢? 答案是肯定的,而且它比你想象的要强大和复杂。Windows 提供了一个名为 Beep 的 API 函数,专门用于生成蜂鸣声。你可能觉得这功能太简单,甚至有点过时——不就是让电脑“哔”一声吗?但恰恰是这个看似简单

weixin_34109408的博客 406

每日一题算法:2020年9月4日 [二叉树的所有路径] binaryTreePaths

2020年9月4日 二叉树的所有路径 binaryTreePaths /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<String&gt

I12XXXXXLbull的博客 239

LLaMA Factory多卡微调的实战教程(持续更新)

本文主要介绍了LLaMA Factory多卡微调的实战教程(持续更新),希望对学习大语言模型的同学们有所帮助。 文章目录 1. 前言 2. 配置环境 2.1 安装虚拟环境 2.2 安装依赖库 2.3 模型选型与下载 2.4 配置多卡环境 3. 运行代码 3.1 构建训练数据 3.2 修改配置文件 3.3 微调 3.3.1 zero3微调 3.3.2 启动API 3.3.3 模型测试

herosunly的博客 25万+

最小二乘(MLS)求点云法向量

MLS算法的基本思想是通过在点云的局部邻域内拟合一个光滑曲面,如平面或多项式曲面,以此来重建和处理点云数据。对于法向量估计,MLS通常在每个点的邻域内拟合局部平面,然后从该平面的法向量作为点的法向量。

twnkie的博客 747

LeetCode-257. Binary Tree Paths (Java)

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"] -------

NOadu的专栏 466

华为OD机试 - 压缩日志查询(Java 双机位C卷 100分)

如:上一行的数据显示范围是202411231540,202411231541542,下一行的数据是显示可以是 202411231544, 202411231547,中间202411231543的数据可能由于其他原因缺失。查询的时间范围为闭区间,即大于等于startTime且小于等于endTime,startTime <= endTime,且他们跨度的分钟数小于100;查询时,根据输入的时间范围进行查询,需要返回回时间范围内记录的每分钟的指标值,如果某个时间点没有记录值,则此条记录忽略不返回。

学Java,找哪吒 1009

java binarytreenode_LeetCode算法题-Binary Tree Paths(Java实现-3种解法)

这是悦乐书的第199次更新,第206篇原创01 看题和准备今天介绍的是LeetCode算法题中Easy级别的第62题(顺位题号是257)。给定二叉树,返回所有根到叶路径。例如:输入:1/ \2 3\5输出:[“1-> 2-> 5”,“1-> 3”]说明:所有根到叶路径是:1-> 2-> 5, 1-> 3注意:叶子是没有子节点的节点。本次解题使用的开发工具是e...

weixin_39594895的博客 207

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

LeetCode Binary Tree Paths

原题链接在这里:https://leetcode.com/problems/binary-tree-paths/ DFS 依次添加,终止条件是叶子节点。 Note: 1. 如果使用StringBuilder, 在递归调用时,必须写成new StringBuilder(sb). 否则会报错. e.g. [1,2,3], 会写成["1->2","1->23"]. 2 . 但如果使用String

Dylan_Java_NYC的博客 521

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

LeetCode题解-257-Binary Tree Paths

原题 原题链接:https://leetcode.com/problems/binary-tree-paths/ 解法概览 解法1:迭代法,后序遍历 解法2:递归法,参考了https://discuss.leetcode.com/topic/23047/clean-java-solution-accepted-without-any-helper-recursive-fun

WangT443的博客 901

LeetCode 257 Binary Tree Paths

题目 Given a binary tree, return all root-to-leaf paths. Note: A leaf is a node with no children. Example: Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"]...

乌鲁木齐001号程序员 105

【LeetCode】257. Binary Tree Paths 二叉树的所有路径(Easy)(JAVA)

【LeetCode】257. Binary Tree Paths 二叉树的所有路径(Easy)(JAVA) 题目地址: https://leetcode.com/problems/binary-tree-paths/ 题目描述: Given a binary tree, return all root-to-leaf paths. Note: A leaf is a node with no children. Example: Input: 1 / \ 2 3 \ 5

qq_16927853的博客 198

【LeetCode】257.Binary Tree Paths(Easy)解题报告

【LeetCode】257.Binary Tree Paths(Easy)解题报告题目地址:https://leetcode.com/problems/binary-tree-paths/description/ 题目描述:   Given a binary tree, return all root-to-leaf paths.   For example, given the f

郝春雨的博客 257

ctf-wiki 堆漏洞利用:ptmalloc2 下 Off-By-One 漏洞原理与 CTF 实战深入剖析

Off-By-One(差一溢出)是 CTF 堆利用中最经典的单字节溢出漏洞类型。本文以 ctf-wiki 仓库中 [Off-By-One 专题文档](https://link.gitcode.com/i/444dea689a91233cbf556ca5e5bf651d) 为主体,系统讲解其产生原理、在 glibc ptmalloc2 堆管理机制下的利用思路,并结合 Asis CTF 2016 b0

gitblog_00432的博客 847

Java描述 LeetCode,257. Binary Tree Paths 二叉树的路径

大家好,我是河海哥,专注于后端,如果可以的话,想做一名code designer而不是普通的coder,一起见证河海哥的成长,您的评论与赞是我的最大动力,如有错误还请不吝赐教,万分感谢。一起支持原创吧!纯手打有笔误还望谅解。 1-1: description Given the root of a binary tree, return all root-to-leaf paths in any order. A leaf is a node with no children. Example 1: .

人在江湖 823

Java [Leetcode 257]Binary Tree Paths

题目描述: 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", "...

dkk37351的博客 121

LeetCode-257. Binary Tree Paths [C++][Java]

Given therootof a binary tree, returnall root-to-leaf paths inany order. Aleafis a node with no children.

贫道绝缘子的博客 273

Leetcode_257_Binary Tree Paths

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/49432057 Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree:

皮斯特劳沃 1563

[LeetCode] Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.For example, given the following binary tree: 1 / \ 2 3 \ 5All root-to-leaf paths are: [“1->2->5”, “1->3”] 解题思路先序遍历,递归的过程中保存路径,遇到叶子节点时将路

楚兴 1081

LeetCode 257. Binary Tree Paths

print all the paths of BT, the out put format should be: [“1->2->5”, “1->3”] clearly, we will use the preorder, but they are not exactly the same. I can’t think of any ways to get this problem done. but based on the solution: binaryTreePath(root)

Tech in Pieces 431

leetcode257 Binary Tree Paths

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"]import java

明天会更好 324
上一篇: LeetCode算法题-Valid Anagram(Java实现)
下一篇: LeetCode算法题-Add Digits(Java实现-3种解法)
程序员小川
博客等级 码龄10年 47粉丝 305原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值