方法1:状态机法
状态由两个部分组成
- 当前树的根节点root
- 辅助Stack的状态
算法就是根据当前的状态,不断跳转到下一个状态,直到root和Stack都为空。Stack里存的是当前树遍历之后再处理的节点,也就是当前树的父亲节点。
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> output = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode pre = null;
while (root != null || stack.size() > 0) {
if (root != null) {
stack.push(root);
root = root.left;
}
else {
root = stack.pop();
if (root.right == null || pre == root.right) { // no right tree or has been handled
output.add(root.val);
pre = root;
root = null;
}
else { //has right child and has not been handled
stack.push(root);
root = root.right;
}
}
}
return output;
}
}
方法2:Working List法
核心是一个Working list,算法不断从中取一个任务进行处理,过程中会产生新的子任务插入到Working list。任务分为两种:
- 复合任务:“后序遍历”以当前节点为根结点的树
- 打印任务:直接打印当前节点的value
对于复合任务的处理:
- 产生3个新的子任务,左右子树的后续遍历任务和当前节点的打印任务
- 新任务插入到队列的顺序很关键,要根据后序遍历的语义要求进行插入。因为这个任务队列是Stack,后处理的任务要先插。
class Solution(object):
def postorderTraversal(self, root):
result, stack = [], [(root, 1)]
if root is None: return result
while len(stack) > 0:
node, taskType = stack.pop()
if taskType == 1: # 1 for traverse job, 插入三个新任务,注意顺序
stack.append((node, 0)) # 0 for basic print job
if node.right is not None: stack.append((node.right, 1))
if node.left is not None: stack.append((node.left, 1))
else: result.append(node.val)
return result
方法3:输出头插法
后序遍历要求根节点最后输出,造成了“先访问到,但是不能输出,只能暂存后续再处理”的处理困境。换个思路,能否访问到就输出?答案是肯定的,只要保证先输出的在输出序列最后,类似链表的头插法,在头部插入,先插入的就在序列最后了。
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> output = new LinkedList<>();
if (root == null) {
return output;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
root = stack.pop();
output.addFirst(root.val);
if (root.left != null) {
stack.push(root.left);
}
if (root.right != null) {
stack.push(root.right);
}
}
return output;
}
}
方法4: 输出序列逆序法
和方法3原理相同,只是不是通过头插进行逆序,而是先正常输出序列,最后再逆序的方式
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> output = new ArrayList<>();
if (root == null) {
return output;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
root = stack.pop();
output.add(root.val);
if (root.left != null) {
stack.push(root.left);
}
if (root.right != null) {
stack.push(root.right);
}
}
Collections.reverse(output);
return output;
}
}