当前位置:网站首页>leetcode刷题:二叉树12(二叉树的所有路径)
leetcode刷题:二叉树12(二叉树的所有路径)
2022-07-05 19:52:00 【涛涛英语学不进去】
257. 二叉树的所有路径
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
显然这题先序遍历比较舒服。使用递归一点点找路。
package com.programmercarl.tree;
import com.programmercarl.util.GenerateTreeNode;
import java.util.ArrayList;
import java.util.List;
/** * @ClassName BinaryTreePaths * @Descriotion TODO * @Author nitaotao * @Date 2022/7/4 18:16 * @Version 1.0 **/
public class BinaryTreePaths {
public static List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<String>();
//先序遍历
getPath(root, result, "");
return result;
}
public static void getPath(TreeNode root, List<String> result, String path) {
// if (root == null) {
// result.add(path.substring(0, path.length() - 2));
// return;
// }
//先序遍历
path += root.val + "->";
//如果接下来只剩一个方向了 选路
if (root.left == null && root.right != null) {
getPath(root.right, result, path);
} else if (root.left != null && root.right == null) {
getPath(root.left, result, path);
} else if (root.left == null && root.right == null){
result.add(path.substring(0, path.length() - 2));
return;
}else{
getPath(root.left, result, path);
getPath(root.right, result, path);
}
}
public static void main(String[] args) {
TreeNode node = GenerateTreeNode.generateTreeNode("[1]");
binaryTreePaths(node);
}
}
边栏推荐
- Autumn byte interviewer asked you any questions? In fact, you have stepped on thunder
- 什么是面上项目
- Android interview, Android audio and video development
- 【硬核干货】数据分析哪家强?选Pandas还是选SQL
- Multi branch structure
- Fundamentals of shell programming (Part 8: branch statements -case in)
- ACM getting started Day1
- leetcode刷题:二叉树17(从中序与后序遍历序列构造二叉树)
- 测试外包公司怎么样?
- 再忙不能忘安全
猜你喜欢
Force buckle 1200 Minimum absolute difference
测试的核心价值到底是什么?
Interviewer: what is the internal implementation of set data types in redis?
[FAQ] summary of common causes and solutions of Huawei account service error 907135701
C application interface development foundation - form control (5) - grouping control
leetcode刷题:二叉树16(路径总和)
秋招字节面试官问你还有什么问题?其实你已经踩雷了
再忙不能忘安全
Do you know several assertion methods commonly used by JMeter?
Bitcoinwin (BCW)受邀参加Hanoi Traders Fair 2022
随机推荐
司空见惯 - 英雄扫雷鼠
如何安全快速地从 Centos迁移到openEuler
函数的概念及语法
Apprentissage du projet MMO I: préchauffage
Let's talk about threadlocalinsecurerandom
S7-200SMART利用V90 MODBUS通信控制库控制V90伺服的具体方法和步骤
IBM大面积辞退40岁+的员工,掌握这十个搜索技巧让你的工作效率至上提高十倍
PHP uses ueditor to upload pictures and add watermarks
Successful entry into Baidu, 35K monthly salary, 2022 Android development interview answer
selenium 元素信息
Is it safe for Anxin securities to open an account online?
Force buckle 729 My schedule I
[Collection - industry solutions] how to build a high-performance data acceleration and data editing platform
深度學習 卷積神經網絡(CNN)基礎
通配符选择器
[untitled]
集合
挖财钱堂教育靠谱安全吗?
What is the core value of testing?
Multi branch structure