后序遍历二叉树
2015-08-16 23:22
337 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/kakabest123/article/details/47709251
递归方法和之前的几乎一致,不再赘述。
考虑非递归方法:
后序遍历顺序是:左,右,根
即左孩子和右孩子都遍历输出了之后,才遍历子树的根节点。
public ArrayList<Integer> postorderTraversal(TreeNode root) { ArrayList<Integer> lst = new ArrayList<Integer>(); if(root == null) return lst; Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); TreeNode prev = null; while(!stack.empty()){ TreeNode curr = stack.peek(); // go down the tree. //check if current node is leaf, if so, process it and pop stack, //otherwise, keep going down if(prev == null || prev.left == curr || prev.right == curr){ //prev == null is the situation for the root node if(curr.left != null){ stack.push(curr.left); }else if(curr.right != null){ stack.push(curr.right); }else{ stack.pop(); lst.add(curr.val); } //go up the tree from left node //need to check if there is a right child //if yes, push it to stack //otherwise, process parent and pop stack }else if(curr.left == prev){ if(curr.right != null){ stack.push(curr.right); }else{ stack.pop(); lst.add(curr.val); } //go up the tree from right node //after coming back from right node, process parent node and pop stack. }else if(curr.right == prev){ stack.pop(); lst.add(curr.val); } prev = curr; } return lst; }
相关文章推荐
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 先序,中序,后序,层次遍历二叉树
- 与二叉树有关的一些操作:先序,中序,后序,层次遍历,计算深度,叶结点数
- 已知二叉树前序,中序遍历,求后序遍历,java实现
- 二叉树的非递归先序,中序,后序遍历
- 剑指Offer——搜索二叉树的后序遍历
- 二叉树的遍历;前序 中序 后序遍历二叉树;递归 非递归实现; 重建二叉树;编程之美重建二叉树
- 二叉树先序遍历,中序遍历,后序遍历递归非递归方法
- 二叉树的先序,中序和后序遍历的非递归算法
- 二叉树的后序遍历的非递归算法(二)
- 二叉树知识点、先序、中序、后序遍历(数据结构)
- 数据结构与算法——二叉树的前序遍历,中序遍历,后序遍历
- 已知先序遍历和中序遍历求后序遍历——二叉树
- 二叉树 BinaryTree (先序、中序、后序遍历 节点查找、插入、删除 完整类) Java数据结构与算法
- 二叉树的后序遍历实现
- 前缀、中缀、后缀表达式与二叉树的前序、中序、后序遍历
- 非递归后序遍历二叉树
- 温习二叉树的建立和先序 中序 后序遍历 嵌套
- 二叉树的创建、前序遍历、中序遍历、后序遍历
- 后序遍历二叉树的两种迭代算法