博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode -- Binary Tree Paths
阅读量:4551 次
发布时间:2019-06-08

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

Question:

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

 

 Analysis:

问题描述:给出一棵二叉树,给出所有根节点到叶子节点的路径。

思路一:递归

Answer:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    List
res = new ArrayList
(); public List
binaryTreePaths(TreeNode root) { if(root != null) findPath(root, Integer.toString(root.val)); return res; } public void findPath(TreeNode root, String string) { // TODO Auto-generated method stub if(root.left == null && root.right == null) res.add(string); if(root.left != null) findPath(root.left, string + "->" + Integer.toString(root.left.val)); if(root.right != null) findPath(root.right, string + "->" + Integer.toString(root.right.val)); }}

思路二:深度优先遍历,用栈保存遍历过的节点。

 

转载于:https://www.cnblogs.com/little-YTMM/p/4844331.html

你可能感兴趣的文章
红帽linux忘记root密码的配置
查看>>
JS十进制转二进制(控制位数)
查看>>
Spark源码分析 – SparkContext
查看>>
tabBar选择不同item设置标题不同颜色
查看>>
机器学习算法一览图
查看>>
【BZOJ】3309: DZY Loves Math 莫比乌斯反演优化
查看>>
luogu1972:HH的项链
查看>>
矩形面积
查看>>
C++语言 文件对话框的调用
查看>>
运算符
查看>>
11.软件项目管理与敏捷方法——风险管理笔记
查看>>
微服务监控zipkin、skywalking以及日志ELK监控系列
查看>>
4553: [Tjoi2016&Heoi2016]序列
查看>>
3027 线段覆盖 2
查看>>
CF 959 E. Mahmoud and Ehab and the xor-MST
查看>>
【niubi-job——一个分布式的任务调度框架】----niubi-job这下更牛逼了!
查看>>
移动支付[1]——MAC加密
查看>>
c++深/浅拷贝 && 构造函数析构函数调用顺序练习题
查看>>
java读取文件夹下所有文件并替换文件每一行中指定的字符串
查看>>
HTML5规范-相关资料链接(大多都是英文文档)
查看>>