二叉树数据结构
顺序存储的二叉树通常只讨论完全二叉树,顺序存储的二叉树,主要是利用数组来实现的。
public class ArrayBinaryTree {
int[] data;
public ArrayBinaryTree(int[] data){
this.data = data;
}
}
二叉树的遍历
首先创建一个如下的二叉树,然后对它进行遍历。
在顺序存储的二叉树中,主要存在以下公式:
第 n 个元素的左子节点是:2*n + 1
第 n 个元素的右子节点是:2*n + 2
第 n 个元素的父结点是:(n-1) / 2
根据以上,可以实现顺序存储的二叉树的遍历:
先序遍历
// 前序遍历
public void frontShow(int index){
if (data == null || data.length == 0){
return;
}
// 先遍历当前节点的内容
System.out.print(data[index] + " ");
// 处理左子树
if (2*index+1 < data.length){
frontShow(2*index+1);
}
//处理右子树
if (2*index+2 < data.length){
frontShow(2*index+2);
}
}
中序遍历
// 中序遍历
public void midShow(int index){
if (data == null || data.length == 0){
return;
}
// 左
if (2*index+1 < data.length){
midShow(2*index+1);
}
// 根
System.out.print(data[index] + " ");
// 右
if (2*index+2 < data.length){
midShow(2*index+2);
}
}
后序遍历
// 后序遍历
public void afterShow(int index){
if (data == null || data.length == 0){
return;
}
// 左
if (2*index+1 < data.length){
afterShow(2*index+1);
}
// 右
if (2*index+2 < data.length){
afterShow(2*index+2);
}
// 根
System.out.print(data[index] + " ");
}
二叉树示例完整代码
二叉树类 ArrayBinaryTree
public class ArrayBinaryTree {
int[] data;
public ArrayBinaryTree(int[] data){
this.data = data;
}
public void frontShow(){
frontShow(0);
}
// 前序遍历
public void frontShow(int index){
if (data == null || data.length == 0){
return;
}
// 先遍历当前节点的内容
System.out.print(data[index] + " ");
// 处理左子树
if (2*index+1 < data.length){
frontShow(2*index+1);
}
//处理右子树
if (2*index+2 < data.length){
frontShow(2*index+2);
}
}
// 中序遍历
public void midShow(int index){
if (data == null || data.length == 0){
return;
}
// 左
if (2*index+1 < data.length){
midShow(2*index+1);
}
// 根
System.out.print(data[index] + " ");
// 右
if (2*index+2 < data.length){
midShow(2*index+2);
}
}
// 后序遍历
public void afterShow(int index){
if (data == null || data.length == 0){
return;
}
// 左
if (2*index+1 < data.length){
afterShow(2*index+1);
}
// 右
if (2*index+2 < data.length){
afterShow(2*index+2);
}
// 根
System.out.print(data[index] + " ");
}
}
测试类 TestArrayBinaryTree
public class TestArrayBinaryTree {
public static void main(String[] args) {
int[] data = new int[] {1, 2, 3, 4, 5, 6, 7}; // 创建二叉树方便,一般用于满二叉树
ArrayBinaryTree tree = new ArrayBinaryTree(data);
System.out.print("先序遍历:");
tree.frontShow();
System.out.println();
System.out.print("中序遍历:");
tree.midShow(0);
System.out.println();
System.out.print("后序遍历:");
tree.afterShow(0);
}
}
运行效果:
先序遍历:1 2 4 5 3 6 7
中序遍历:4 2 5 1 6 3 7
后序遍历:4 5 2 6 7 3 1