package com.quan.test;
import com.quan.bean.TreeNode;
import java.util.Stack;
public class PrintBinaryTree {
// Test
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(7);
inOrderUnRecur(root);
preOrderUnRecur(root);
postOrderUnRecur(root);
}
// Inorder print with no recurrence
// 1. 准备一个栈,将根节点入栈
// 2. top指针指向栈顶元素,如果栈顶元素左子树不为空,将左节点入栈
// 3. 如果左子树为空,pop出栈顶元素并打印栈顶元素。
// 如果pop出的元素右子树不为空,将右节点入栈,否则什么不做
public static void inOrderUnRecur(TreeNode root) {
if (root == null) {
return ;
}
// 申请一个栈stack,将根节点入栈,另外一个栈printed记录打印过的节点。
Stack<TreeNode> stack = new Stack<>();
Stack<TreeNode> printed = new Stack<>();
stack.push(root);
// 栈不为空,代表输出没有结束
while (!stack.isEmpty()) {
// 获取栈顶元素
TreeNode top = stack.peek();
// 栈顶元素有左子树,且没有打印过,将左节点入栈
if (top.left != null && !printed.contains(top.left)) {
stack.push(top.left);
}
// 栈顶元素没有左子树,将该元素打印,因为右子树上的节点都应该在中间节点之后打印
else {
// 打印该元素的值
System.out.print(stack.pop().val);
printed.push(top);
// 如果该元素有右子树,将右节点入栈
if (top.right != null) {
stack.push(top.right);
}
}
}
System.out.println();
}
// 中左右
public static void preOrderUnRecur(TreeNode root) {
if (root == null) {
return ;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode top = stack.pop();
System.out.print(top.val);
if (top.right != null) {
stack.push(top.right);
}
if (top.left != null) {
stack.push(top.left);
}
}
System.out.println();
}
// 左右中
public static void postOrderUnRecur(TreeNode root) {
if (root == null) {
return ;
}
Stack<TreeNode> stack = new Stack<>();
Stack<TreeNode> reverse_stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode top = stack.pop();
reverse_stack.push(top);
if (top.left != null) {
stack.push(top.left);
}
if (top.right != null) {
stack.push(top.right);
}
}
while (!reverse_stack.isEmpty()) {
System.out.print(reverse_stack.pop().val);
}
System.out.println();
}
}
二叉树的前中后序非递归Java实现
最新推荐文章于 2023-04-02 07:00:00 发布