import java.util.*;
/**
* @author lwy
* @create 2022-04-05 14:23
*/
public class BinaryTreePostOrder {
static class Node {
int val;
Node left;
Node right;
Node() {
}
Node(int value) {
this.val = value;
}
Node(int value, Node left, Node right) {
this.val = value;
this.left = left;
this.right = right;
}
}
public static void main(String[] args) {
// todo
}
// 第一种迭代后序遍历(常规)
public static List<Integer> postOrder1(Node node) {
List<Integer> res = new ArrayList<>();
Stack<Node> st = new Stack<>();
Node prev = null;
Node cur = node;
while (cur != null || !st.isEmpty()) {
while (cur != null) {
st.push(cur);
cur = cur.left;
}
if (!st.isEmpty()) {
cur = st.pop();
// 当前结点的右孩子为空,或者已经被访问
if (cur.right == null || prev == cur.right) {
res.add(cur.val);
prev = cur;
cur = null;
} else {
st.push(cur);
cur = cur.right;
}
}
}
return res;
}
// 第二种迭代后序遍历
public static List<Integer> postOrder2(Node node) {
List<Integer> res = new ArrayList<>();
Stack<Node> st = new Stack<>();
if (node == null) {
return res;
} else {
st.push(node);
}
while (!st.isEmpty()) {
Node cur = st.peek();
if (cur != null) {
// 将该节点弹出,避免重复操作,下面再将右中左节点添加到栈中
st.push(cur);
// 添加中节点
st.push(null);
// 中节点访问过,但是还没有处理,加入空节点做为标记
st.pop();
// 添加右节点(空节点不入栈)
if (cur.right != null) {
st.push(cur.right);
}
// 添加左节点(空节点不入栈)
if (cur.left != null) {
st.push(cur.left);
}
} else {
// 弹出“null”
st.pop();
// 重新取出栈中元素
Node tmp = st.peek();
st.pop();
// 加入到结果集
res.add(tmp.val);
}
}
return res;
}
// 第三种迭代后序遍历
// 后序遍历顺序 左-右-中 入栈顺序:中-左-右 出栈顺序:中-右-左, 最后翻转结果
public static List<Integer> postOrder3(Node node) {
List<Integer> res = new ArrayList<>();
Stack<Node> st = new Stack<>();
if (node == null) {
return res;
} else {
st.push(node);
}
while (!st.isEmpty()) {
Node cur = st.pop();
res.add(node.val);
if (node.left != null) {
st.push(node.left);
}
if (node.right != null) {
st.push(node.right);
}
}
Collections.reverse(res);
return res;
}
// 递归后续遍历
public static void postOrder4(Node node, List<Integer> res) {
if (node == null) {
return;
}
postOrder4(node.left, res);
postOrder4(node.right, res);
res.add(node.val);
}
}