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

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

示例:

输入:

1
/ \
2 3
\
5

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

解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

首先来看递归版本:

 static void dfs(TreeNode root, String path, LinkedList<String> paths){
if(root.left == null && root.right ==null){
paths.add(path + root.val);
return;
}
if(root.left != null) {
dfs(root.left, path + root.val + "->", paths);
}
if(root.right != null ) {
dfs(root.right, path + root.val + "->", paths);
}
}
public static List<String> binaryTreePaths(TreeNode root) {
LinkedList<String> paths = new LinkedList();
//递归版本
// dfs(root, "", paths);
return paths;
}

那么如何将其改为非递归版本呢,我们利用后序遍历模板与先序遍历模板来实现。

解法一

static void iteration(TreeNode root, LinkedList<String> paths) {

        Stack<TreeNode> s = new Stack<>();
TreeNode p = root;
TreeNode pre = null; while(p != null ){
s.push(p);
p = p.left ;
} while(!s.empty()){
p = s.peek();
if(p.right!=null && p.right != pre){
p = p.right;
while(p != null ){
s.push(p);
p = p.left ;
}
pre =null;
}
else{
if(pre == null ) {
paths.add(getPath(s, "->")); }
pre = s.pop();
}
}
System.out.println();
}
public static List<String> binaryTreePaths(TreeNode root) {
LinkedList<String> paths = new LinkedList();
//递归版本
// dfs(root, "", paths);
//非递归版本
iteration(root, paths);
return paths;
}
private static String getPath(Stack<TreeNode> s, String sp) {
// Iterator<TreeNode> it = s.iterator();
StringBuilder buf = new StringBuilder();
// while (it.hasNext()) {
// if (buf.length() != 0) {
// buf.append(sp);
// }
// buf.append(String.valueOf(it.next().value));
// } for(TreeNode node : s){
if (buf.length() != 0) {
buf.append(sp);
}
buf.append(String.valueOf(node.val));
}
return buf.toString();
}
 

解法二

class Solution {
public List<String> binaryTreePaths(TreeNode root) {
LinkedList<String> paths = new LinkedList();
if (root == null)
return paths; LinkedList<TreeNode> node_stack = new LinkedList();
LinkedList<String> path_stack = new LinkedList();
node_stack.add(root);
path_stack.add(Integer.toString(root.val));
TreeNode node;
String path;
while (!node_stack.isEmpty()) {
node = node_stack.pollLast();
path = path_stack.pollLast();
if ((node.left == null) && (node.right == null))
paths.add(path);
if (node.left != null) {
node_stack.add(node.left);
path_stack.add(path + "->" + Integer.toString(node.left.val));
}
if (node.right != null) {
node_stack.add(node.right);
path_stack.add(path + "->" + Integer.toString(node.right.val));
}
}
return paths;
}
}

在这里我们用两种模板完整地实现二叉树的先序遍历,中序遍历,后序遍历。

思想一:  在从栈里弹出节点的时候,此时压入左右节点

public static void  PreOrderTraversal(TreeNode root){
Stack<TreeNode> s = new Stack<>(); TreeNode p = root;
s.push(p);
while(!s.empty()){ TreeNode node = s.pop();
if(node == null ){
continue;
}
System.out.print(node.val+" ");
if(node.right != null ) {
s.push(node.right);
}
if(node.left != null ){
s.push(node.left);
}
}
System.out.println();
} public static void PostOrderTraversal(TreeNode root){
List<Integer> res = new ArrayList<>();
Stack<TreeNode> s = new Stack<>(); TreeNode p = root;
s.push(p);
while(!s.empty()){ TreeNode node = s.pop();
if(node == null ){
continue;
}
// System.out.print(node.val+" ");
res.add(node.val);
if(node.left != null ) {
s.push(node.left);
}
if(node.right != null ){
s.push(node.right);
}
}
Collections.reverse(res);
System.out.println(res);
}

 思想二: 从栈中弹出节点的时候,一直压入左孩子,直到为空,对于栈顶节点来说,如果有右孩子,压入右孩子,否则一直弹。

后序遍历比较特殊,对于某一节点来说,需要判断是从左右节点哪个节点访问。

    public static void  PreOrderWithoutRecursion(TreeNode root){
Stack<TreeNode> s = new Stack<>(); TreeNode p = root;
while(p != null || !s.empty()){
if(p != null ){
System.out.print(p.val +" ");
s.push(p);
p = p.left ;
} else{
p = s.pop();
p = p .right; }
}
System.out.println();
} public static void InOrderWithoutRecursion(TreeNode root){
Stack<TreeNode> s = new Stack<>(); TreeNode p = root;
while(p != null || !s.empty()){
if(p != null ){
s.push(p);
p = p.left ;
} else{
p = s.pop();
System.out.print(p.val +" ");
p = p.right; }
}
System.out.println();
} public static void PostOrderWithoutRecursion(TreeNode root){
Stack<TreeNode> s = new Stack<>(); TreeNode p = root;
TreeNode pLastVistNode = null; while(p != null ){
s.push(p);
p = p.left ;
} while(!s.empty()){
p = s.pop();
if( p.right == null || p.right == pLastVistNode){
System.out.print(p.val+" ");
pLastVistNode = p;
}
else{
s.push(p);
p = p.right;
while(p != null){
s.push(p);
p = p.left;
}
}
}
System.out.println();
}

leetcode 257. 二叉树的所有路径 包含(二叉树的先序遍历、中序遍历、后序遍历)的更多相关文章

  1. LeetCode 145. 二叉树的后序遍历 (用栈实现后序遍历二叉树的非递归算法)

    题目链接:https://leetcode-cn.com/problems/binary-tree-postorder-traversal/ 给定一个二叉树,返回它的 后序 遍历. 示例: 输入: [ ...

  2. PAT树_层序遍历叶节点、中序建树后序输出、AVL树的根、二叉树路径存在性判定、奇妙的完全二叉搜索树、最小堆路径、文件路由

    03-树1. List Leaves (25) Given a tree, you are supposed to list all the leaves in the order of top do ...

  3. [leetcode]从中序与后序/前序遍历序列构造二叉树

    从中序与后序遍历序列构造二叉树 根据一棵树的中序遍历与后序遍历构造二叉树. 注意: 你可以假设树中没有重复的元素. 例如,给出 中序遍历 inorder = [9,3,15,20,7] 后序遍历 po ...

  4. Leetcode(106)-从中序与后序遍历序列构造二叉树

    根据一棵树的中序遍历与后序遍历构造二叉树. 注意:你可以假设树中没有重复的元素. 例如,给出 中序遍历 inorder = [9,3,15,20,7] 后序遍历 postorder = [9,15,7 ...

  5. (原)neuq oj 1022给定二叉树的前序遍历和后序遍历确定二叉树的个数

    题目描述 众所周知,遍历一棵二叉树就是按某条搜索路径巡访其中每个结点,使得每个结点均被访问一次,而且仅被访问一次.最常使用的有三种遍历的方式: 1.前序遍历:若二叉树为空,则空操作:否则先访问根结点, ...

  6. 小小c#算法题 - 11 - 二叉树的构造及先序遍历、中序遍历、后序遍历

    在上一篇文章 小小c#算法题 - 10 - 求树的深度中,用到了树的数据结构,树型结构是一类重要的非线性数据结构,树是以分支关系定义的层次结构,是n(n>=0)个结点的有限集.但在那篇文章中,只 ...

  7. 二叉排序树的构造 && 二叉树的先序、中序、后序遍历 && 树的括号表示规则

    二叉排序树的中序遍历就是按照关键字的从小到大顺序输出(先序和后序可没有这个顺序) 一.以序列 6 8 5 7 9 3构建二叉排序树: 二叉排序树就是中序遍历之后是有序的: 构造二叉排序树步骤如下: 插 ...

  8. 二叉树后序遍历的非递归算法(C语言)

    首先非常感谢‘hicjiajia’的博文:二叉树后序遍历(非递归) 这篇随笔开启我的博客进程,成为万千程序员中的一员,坚持走到更远! 折磨了我一下午的后序遍历中午得到解决,关键在于标记右子树是否被访问 ...

  9. LintCode2016年8月8日算法比赛----中序遍历和后序遍历构造二叉树

    中序遍历和后序遍历构造二叉树 题目描述 根据中序遍历和后序遍历构造二叉树 注意事项 你可以假设树中不存在相同数值的节点 样例 给出树的中序遍历: [1,2,3] 和后序遍历: [1,3,2] 返回如下 ...

随机推荐

  1. GPU Debugger

    https://gpuopen.com/presentations/2019/digital-dragons-2019-make-your-game-friendly.pdf https://grap ...

  2. 在Google Maps 上点击标签后显示说明

    JS如下: (function() {     window.onload = function() {           // Creating an object literal contain ...

  3. Mybatis resultMap和resultType的区别

    resultType和resultMap功能类似  ,都是返回对象信息  ,但是resultMap要更强大一些 ,可自定义.因为resultMap要配置一下,表和类的一一对应关系,所以说就算你的字段名 ...

  4. 解决蓝牙鼠标在 Ubuntu 中单位时间内断开的问题

    1 查询你的鼠标的蓝牙地址 1.1 如:E1:DE:02:05:5E:F5 2 将查询到的设备地址写入配置文件 /etc/bluetooth/main.conf # Use vendor id sou ...

  5. Ubuntu16.04下安装多版本cuda和cudnn

    Ubuntu16.04下安装多版本cuda和cudnn 原文 https://blog.csdn.net/tunhuzhuang1836/article/details/79545625 前言 因为之 ...

  6. python基本数据类型剖析

    一. 基本数据类型常用功能:1. 整数 int #int内部优化 n1=123 n2=n1 n1= 123 n2= 123 ========2份内存========= if -5~257: n1= 1 ...

  7. codeforces#999 E. Reachability from the Capital(图论加边)

    题目链接: https://codeforces.com/contest/999/problem/E 题意: 在有向图中加边,让$S$点可以到达所有点 数据范围: $ 1 \leq n \leq 50 ...

  8. JavaWeb_(Mybatis框架)JDBC操作数据库和Mybatis框架操作数据库区别_一

    系列博文: JavaWeb_(Mybatis框架)JDBC操作数据库和Mybatis框架操作数据库区别_一 传送门 JavaWeb_(Mybatis框架)使用Mybatis对表进行增.删.改.查操作_ ...

  9. 2018-2019-2 20165330《网络对抗技术》Exp7 网络欺诈防范

    目录 基础问题 相关知识 实验目的 实验内容 实验步骤 实验中遇到的问题 实验总结与体会 实验目的 本实践的目标理解常用网络欺诈背后的原理,以提高防范意识,并提出具体防范方法. 返回目录 实验内容 简 ...

  10. 更新ubuntu的对应源配置文件

    UBUNTU中安装依赖包,出现如下错误:E: Failed to fetch http://security.ubuntu.com/ubuntu/pool/universe/o/openjdk-8/o ...