实现二叉树的先序、中序、后序遍历,包括递归方式和非递归方式
程序员文章站
2022-05-16 10:08:55
...
实现二叉树的先序、中序、后序遍历,包括递归方式和非递归方式
public class BinaryTree {
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int value) {
this.value = value;
}
}
// 递归先序遍历二叉树
public static void preOrderRecur(Node head) {
if (head == null) {
return;
}
System.out.print(head.value + " ");
preOrderRecur(head.left);
preOrderRecur(head.right);
}
// 递归中序遍历二叉树
public static void inOrderRecur(Node head) {
if (head == null) {
return;
}
inOrderRecur(head.left);
System.out.print(head.value + " ");
inOrderRecur(head.right);
}
// 递归后序遍历二叉树
public static void posOrderRecur(Node head) {
if (head == null) {
return;
}
posOrderRecur(head.left);
posOrderRecur(head.right);
System.out.print(head.value + " ");
}
// 非递归先序遍历二叉树
public static void preOrderUnRecur(Node head) {
System.out.print("pre-order: ");
if (head != null) {
Stack<Node> stack = new Stack<Node>();
stack.add(head);
while (!stack.isEmpty()) {
head = stack.pop();
System.out.print(head.value + " ");
if (head.right != null) {
stack.push(head.right);
}
if (head.left != null) {
stack.push(head.left);
}
}
}
System.out.println();
}
// 非递归中序遍历二叉树
public static void inOrderUnRecur(Node head) {
System.out.print("in-order: ");
if (head != null) {
Stack<Node> stack = new Stack<Node>();
while (!stack.isEmpty() || head != null) {
if (head != null) {
stack.push(head);
head = head.left;
} else {
head = stack.pop();
System.out.print(head.value + " ");
head = head.right;
}
}
}
System.out.println();
}
// 非递归后序遍历二叉树
public static void posOrderUnRecur(Node head) {
System.out.print("pos-order: ");
if (head != null) {
Stack<Node> s1 = new Stack<Node>();
Stack<Node> s2 = new Stack<Node>();
s1.push(head);
while (!s1.isEmpty()) {
head = s1.pop();
s2.push(head);
if (head.left != null) {
s1.push(head.left);
}
if (head.right != null) {
s1.push(head.right);
}
}
while (!s2.isEmpty()) {
System.out.print(s2.pop().value + " ");
}
}
System.out.println();
}
}
下一篇: 二叉树的先序、中序、后序遍历的非递归方式
推荐阅读
-
Python实现输入二叉树的先序和中序遍历,再输出后序遍历操作示例
-
PHP基于非递归算法实现先序、中序及后序遍历二叉树操作示例
-
左神算法:分别用递归和非递归方式实现二叉树先序、中序和后序遍历(Java版)
-
二分搜索树 BST 前序\中序\后序(递归和非递归实现)和层序遍历
-
PHP基于非递归算法实现先序、中序及后序遍历二叉树操作示例
-
Java实现二叉树先序、中序、后序遍历(递归与非递归)及层次遍历
-
JAVA 实现二叉树建立和先序,中序和后序遍历(递归与非递归)
-
非递归实现二叉树先序、中序、后序遍历(栈实现)
-
java实现二叉树的前序、中序、后序、层次遍历,递归与非递归
-
LeetCode 二叉树的中序遍历(递归和非递归算法)