二叉树的初始化:
package BinaryTree;
public class BinaryTree {
int data;//父结点
BinaryTree leftTree;//左子结点
BinaryTree rightTree;//右子结点
public BinaryTree(int data) {
this.data = data;
leftTree = null;
rightTree = null;
}
/**
*二叉树的右子结点比父结点大 左子结点比父结点小
*/
public void insert(BinaryTree root, int data) {
if (data > root.data) {
if (root.rightTree == null) {
root.rightTree = new BinaryTree(data);
} else {
this.insert(root.rightTree, data);
}
} else {
if (root.leftTree == null) {
root.leftTree = new BinaryTree(data);
} else {
this.insert(root.leftTree, data);
}
}
}
}
二叉树遍历:
package BinaryTree;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
public class Order {
/**
* 前序遍历
* @param root
*/
public static void preorder(BinaryTree root){
if(root != null){
System.out.print(root.data + " ");
preorder(root.leftTree);
preorder(root.rightTree);
}
}
/**
* 中序遍历
* @param root
*/
public static void inorder(BinaryTree root){
if(root != null){
inorder(root.leftTree);
System.out.print(root.data + " ");
inorder(root.rightTree);
}
}
/**
* 后序遍历
* @param root
*/
public static void postorder(BinaryTree root){
if(root != null){
postorder(root.leftTree);
postorder(root.rightTree);
System.out.print(root.data + " ");
}
}
/**
* 层序遍历 利用队列先进先出来进行层层遍历
* @param root
*/
public static void sequenceorder(BinaryTree root){
if(root != null){
Queue<BinaryTree> queue = new LinkedBlockingQueue<>();
BinaryTree binaryTree;
queue.add(root);//将已初始化二叉树根结点放入队列之中
while (!queue.isEmpty()){
binaryTree = queue.remove();
System.out.print(binaryTree.data + " ");//每次将上次进入队列的结点输出
if(binaryTree.leftTree != null){
queue.add(binaryTree.leftTree);
}
if(binaryTree.rightTree != null){
queue.add(binaryTree.rightTree);
}
}
}
}
}
测试:
package BinaryTree;
public class MyTest {
public static void main(String[] args) {
int []arr = {13, 1, 2, 25, 39, 59, 79, 22, 34, 28, 37};
BinaryTree binaryTree = new BinaryTree(arr[0]);//初始化根结点
for (int i = 1; i < arr.length; i++) {
binaryTree.insert(binaryTree, arr[i]);//初始化二叉树
}
System.out.println("先序遍历");
Order.preorder(binaryTree);
System.out.println();
System.out.println("中序遍历");
Order.inorder(binaryTree);
System.out.println();
System.out.println("后序遍历");
Order.postorder(binaryTree);
System.out.println();
System.out.println("层序遍历");
Order.sequenceorder(binaryTree);
}
}
输出结果:
先序遍历
13 1 2 25 22 39 34 28 37 59 79
中序遍历
1 2 13 22 25 28 34 37 39 59 79
后序遍历
2 1 22 28 37 34 79 59 39 25 13
层序遍历
13 1 25 2 22 39 34 59 28 37 79
Process finished with exit code 0
二叉树的定义、性质及遍历方法:https://blog.csdn.net/a572463931/article/details/106094769