二叉树的后序遍历(递归和非递归)
来源:互联网 发布:问卷星如何录入数据 编辑:程序博客网 时间:2024/06/05 09:36
对于二叉树的后序遍历,最常用的就是递归,代码清晰,如下:
ArrayList<Integer> list = new ArrayList<>(); public ArrayList<Integer> postorderTraversal(TreeNode root) { if(root == null) return list; sort(root); return list; } private void sort(TreeNode root){ if(root == null) return; sort(root.left); sort(root.right); list.add(root.val); }
但是当二叉树高度很大的时候,递归就容易导致栈溢出,所以就需要将递归改为非递归方式,代码如下:
public ArrayList<Integer> postorderTraversal(TreeNode root) { ArrayList<Integer> list = new ArrayList<>(); if(root == null) return list; Stack<TreeNode> s = new Stack<>(); TreeNode p = root; TreeNode r = null;//用来记录上次被访问的节点 while(p != null || !s.isEmpty()){ if(p != null){ s.push(p); p = p.left; }else{ p = s.peek(); p = p.right; if(p != null && p != r){ s.push(p); p = p.left; }else{ p = s.pop(); list.add(p.val); r = p; p = null; } } } return list; }
阅读全文
0 0
- 数据结构:二叉树的前序,中序,后序遍历(递归和非递归)
- 二叉树的递归和非递归遍历(前序、中序、后序)
- 二叉树的后序遍历(递归和非递归)
- 二叉树的后序递归,非递归遍历
- 二叉树非递归后序遍历(非递归遍历中最麻烦的一个)
- 【二叉树】 前序、中序和后序的递归遍历与非递归遍历
- 二叉树的先序、中序、后序递归遍历和非递归遍历
- 二叉树的后序遍历(非递归)
- 二叉树的遍历(后序)-非递归实现
- 二叉树的前、中、后序遍历(递归和非递归)、层序遍历、深度、叶子节点个数
- 二叉树详解及二叉树的前序、中序、后序遍历(递归和非递归)
- 二叉树的先序、中序、后序遍历的递归和非递归实现
- 二叉树的创建和先序,中序,后序,递归,非递归遍历
- 二叉树的前序,中序,后序遍历。用递归和非递归实现
- 二叉树的递归和非递归前、中、后序遍历
- 二叉树的遍历(递归和非递归)
- 二叉树的遍历(递归和非递归)
- 二叉树的建立和遍历(递归、非递归)
- NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
- 通过代码创建新的窗体
- 关于Vue中v-show中添加表达式用于判断是否显示的问题
- JavaScript 开发人员需要知道的简写技巧
- c++中冒号(:)和双冒号(::)的用法
- 二叉树的后序遍历(递归和非递归)
- AOP面向切面编程
- 第九周 项目1
- python语法
- c#构造函数练习
- 第9周项目1 二叉树算法库
- Unindexed remote maven repositories found 关于idea 创建任务报错的解决方法
- 榜样的力量!「金猿奖」2017数据智能新锐人物奖获奖名单揭晓
- libmysqlclient.so.18: cannot open shared object file: No such file or directory