一、前序遍历:根 -> 左 -> 右
1、以递归的方式前序遍历二叉树
public static void preorderByRecursion(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
list.add(root.value);
preorderByRecursion(root.left, list);
preorderByRecursion(root.right, list);
}
2、以栈的方式前序遍历二叉树
public static void preorderByStack(TreeNode root, List<Integer> list) {
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.empty()) {
while (root != null) {
list.add(root.value);
stack.push(root);
root = root.left;
}
if (!stack.empty()) {
root = stack.pop().right;
}
}
}
二、中序遍历:左 -> 根 -> 右
1、以递归的方式中序遍历二叉树
public static void inorderByRecursion(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
inorderByRecursion(root.left, list);
list.add(root.value);
inorderByRecursion(root.right, list);
}
2、以栈的方式中序遍历二叉树
public static void inorderByStack(TreeNode root, List<Integer> list) {
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.empty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
if (!stack.empty()) {
root = stack.pop();
list.add(root.value);
root = root.right;
}
}
}
三、后序遍历:左 -> 右 -> 根
1、以递归的方式后序遍历二叉树
public static void postorderByRecursion(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
postorderByRecursion(root.left, list);
postorderByRecursion(root.right, list);
list.add(root.value);
}
2、以栈的方式后序遍历二叉树
public static void postorderByStackInRight(TreeNode root, List<Integer> list) {
Stack<TreeNode> nodeStack = new Stack<>();
Stack<Integer> resultStack = new Stack<>();
while (root != null || !nodeStack.empty()) {
while (root != null) {
nodeStack.push(root);
resultStack.push(root.value);
root = root.right;
}
if (!nodeStack.empty()) {
root = nodeStack.pop().left;
}
}
while (!resultStack.empty()) {
list.add(resultStack.pop());
}
}