LeetCode 145 Binary Tree Postorder Traversal
来源:互联网 发布:ios编程入门 编辑:程序博客网 时间:2024/04/29 10:02
二叉树的非递归后序遍历
普通认为后序遍历的非递归方式比前序和中序要难,难在什么地方呢。
首先,后序遍历的顺序是左子树-》右子树-》根节点
假如按照中序和前序的想法进行,首先用stack压入左子树的左孩子节点,直到左节点为空;那每次栈弹出的顺序肯定就是左孩子节点-》父节点。一旦父节点弹出栈,遍历完右子树之后,就无法返回了。这是我们经常卡住的地方。
public List<Integer> postorderTraversal(TreeNode root){List<Integer> list = new ArrayList<Integer>();Stack<TreeNode> stack = new Stack<TreeNode>();TreeNode current = root;while(!stack.isEmpty()||current!=null){if(current!=null){stack.push(current);current=current.left;}else{current=stack.pop();if(current.right!=null)//如果右孩子不为空,重新入栈{ stack.push(current);}else{ list.add(current.val); if(!stack.isEmpty()){ if(stack.peek().right==current) { stack.peek().right=null; }else { stack.peek().left=null; } }} current=current.right;}}return list;}
这种方法的缺点是:破坏了树的原有结构,遍历过程相当于拆树的过程。
0 0
- LeetCode(145)Binary Tree Postorder Traversal
- LeetCode: Binary Tree Postorder Traversal [145]
- LeetCode 145 Binary Tree Postorder Traversal
- LeetCode 145 Binary Tree Postorder Traversal
- leetcode || 145、Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal - LeetCode 145
- Leetcode[145]-Binary Tree Postorder Traversal
- LeetCode 145 Binary Tree Postorder Traversal
- leetcode(145):Binary Tree Postorder Traversal
- leetcode-145-Binary Tree Postorder Traversal
- [Leetcode 145, Hard] Binary Tree Postorder Traversal
- leetcode[145]:Binary Tree Postorder Traversal
- [leetcode-145]Binary Tree Postorder Traversal(c++)
- Leetcode #145 Binary Tree Postorder Traversal
- LeetCode 145 : Binary Tree Postorder Traversal
- LeetCode 145: Binary Tree Postorder Traversal
- 【LEETCODE】145-Binary Tree Postorder Traversal
- LeetCode 145 Binary Tree Postorder Traversal
- Android系列之网络(一)----使用HttpClient发送HTTP请求(通过get方法获取数据)
- JavaBean入门 - 概念和简单例子
- 高并发Web服务的演变——节约系统内存和CPU
- KMP字符串模式匹配详解
- SUSE Linux 安装FTP
- LeetCode 145 Binary Tree Postorder Traversal
- Android切换飞行模式(SDK4.2之前或之后都可用)
- Qt 布局管理器
- 《实体解析与信息质量》-1.2.5.实体关系分析
- eclipse中 起动tomcat时报Multiple Contexts have a path of "/shopping"
- 【数据结构】二叉树的一个应用,哈夫曼编码的生成
- Android网络之数据解析----SAX方式解析XML数据
- 对话万维网发明者伯纳斯·李 探讨科技的未来
- 教大家如何将自己的软件变成系统软件