LeetCode 145 Binary Tree Postorder Traversal
来源:互联网 发布:销售数据分析指标 编辑:程序博客网 时间:2024/05/16 09:41
题目描述
Given a binary tree, return the postorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3},
1 \ 2 / 3
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
分析
后序遍历比前序遍历、中序遍历复杂一些,主要体现在判断一个结点出栈时,如果是第一次出栈,则还需入栈。因为后序遍历是“左右中”的顺序。
可以给每个结点增加一个布尔值,用来判断是否是第一次出栈。可以定义如下的数据结构:
public static class PostTreeNode { TreeNode node; boolean first; }
其中first用来判断是否是第一次出栈。
代码
public static class PostTreeNode { TreeNode node; boolean first; } public static List<Integer> postorderTraversal(TreeNode root) { List<Integer> rt = new ArrayList<Integer>(); if (root == null) { return rt; } Stack<PostTreeNode> stack = new Stack<PostTreeNode>(); TreeNode p = root; PostTreeNode t; while (p != null || !stack.empty()) { while (p != null) { // 新建一个结点,这个结点包含一个布尔值first // 用来判断是否是第一次入栈 PostTreeNode post = new PostTreeNode(); post.node = p; post.first = true; stack.push(post); p = p.left; } if (!stack.empty()) { t = stack.pop(); // 如果结点第一次出栈,再次入栈,将first置为false if (t.first == true) { t.first = false; stack.push(t); p = t.node.right; } else { rt.add(t.node.val); p = null; } } } return rt; }
1 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
- Redis的“表”怎么设计的?
- 十二月伊始。
- Protobuf与Json互转
- SpringMVC_post乱码
- Linux内核的信号机制——怪胎
- LeetCode 145 Binary Tree Postorder Traversal
- IGMP Snooping
- 安卓Android控件ListView获取item中EditText值
- C++继承总结
- HDU 4619 (二分图匹配 最大独立集)
- PHP自带邮件发送配置
- MyBatis 学习笔记一
- Github添加SSH Key
- POJ 1797 Heavy Transportation