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

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

示例:

输入:

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. 牛客练习赛53 E 老瞎眼 pk 小鲜肉 (线段树,思维)

    链接:https://ac.nowcoder.com/acm/contest/1114/E来源:牛客网 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 524288K,其他语言1048 ...

  2. KeyboardEvent keyCode Property

    Definition and Usage The keyCode property returns the Unicode character code of the key that trigger ...

  3. 【转载】总结:几种生成HTML格式测试报告的方法

    总结:几种生成HTML格式测试报告的方法 写自动化测试时,一个很重要的任务就是生成漂亮的测试报告. 1.用junit或testNg时,可以用ant辅助生成html格式: <target name ...

  4. mysql_config_editor设置

    [root@node01 etc]# mysql_config_editor set -G mysql3307 -S /tmp/mysql3307.sock -uroot -pEnter passwo ...

  5. 【转载】解决繁体、日文游戏乱码的五种方法 转载自:http://tieba.baidu.com/p/488627981

    方法1:转换区域 开始——设置——控制面板——区域和语言选项——分别选择“高级”和“区域选项”标签——在其下拉框中都选择“日语”(或“日本”)(选项有点多,慢慢找)——重启后即可生效. *某影注:日语 ...

  6. 制作 leanote docker 镜像 并运行

    # 1.制作基础镜像 leanote 使用 mongodb 存储数据,如果把 mongodb 单独做成一个镜像,初始化数据时比较麻烦,所以最后还是决定把 mongodb 和 leanote 放到同一个 ...

  7. unity 用代码控制动画的播放的进度

    https://answers.unity.com/questions/1225328/imported-animated-object-and-slider-tutorial.html using ...

  8. 方程的解——枚举&&水题

    题目 链接 给出方程组:$$\displaystyle \left\{\begin{aligned}11x + 13y + 17z = 2471 \\13x + 17y + 11z = 2739\en ...

  9. Spring Boot 前期篇

    在学习springboot之前,学习一下Spring的java配置. 1. Spring的发展 1.1. Spring1.x 时代 在Spring1.x时代,都是通过xml文件配置bean,随着项目的 ...

  10. AtCoder Beginner Contest 137 D题【贪心】

    [题意]一共有N个任务和M天,一个人一天只能做一个任务,做完任务之后可以在这一天之后的(Ai-1)天拿到Bi的工资,问M天内最多可以拿到多少工资. 链接:https://atcoder.jp/cont ...