顺序储存二叉树
基本说明:从数据存储来看,数组存储方式和树的存储方式可以相互转换,即数组可以转换成树,树也可以转换成数组
要求
1.以数组的方式来存放
2.遍历数组时,仍然可以用前序遍历,中序遍历,后序遍历的方式完成结点的遍历
特点
1.顺序二叉树通常只考虑完全二叉树
2.n表示二叉树中元素的下标,从0开始编号,n+1表示二叉树中第几个元素
3.下标为n的元素的左子节点对应的数组下标为2 * n + 1
4.下标为n的元素的右子节点对应的数组下标为2 * n + 2
5.下标为n的元素的父节点对应的数组下标为(n - 1) / 2
代码实现
public class ArrayBinaryTree {
private int[] arr;// 存储数据结点的数组
public ArrayBinaryTree(int[] arr) {
this.arr = arr;
}
//重载preList,因为固定从根节点开始遍历
public void preList() {
this.preList(0);
}
public void preList(int index) {
if (arr == null || arr.length == 0) {
System.out.println("数组为空");
}
System.out.println(arr[index]);//输出当前元素
if ((index * 2 + 1) < arr.length) {//向左递归遍历
preList(2 * index + 1);
}
if ((index * 2 + 2) < arr.length) {//向右递归遍历
preList(2 * index + 2);
}
}
//重载infixList,因为固定从根节点开始遍历
public void infixList() {
this.infixList(0);
}
public void infixList(int index) {
if (arr == null || arr.length == 0) {
System.out.println("数组为空");
}
if ((index * 2 + 1) < arr.length) {//向左递归遍历
infixList(2 * index + 1);
}
System.out.println(arr[index]);//输出当前元素
if ((index * 2 + 2) < arr.length) {//向右递归遍历
infixList(2 * index + 2);
}
}
//重载postList,因为固定从根节点开始遍历
public void postList() {
this.postList(0);
}
public void postList(int index) {
if (arr == null || arr.length == 0) {
System.out.println("数组为空");
}
if ((index * 2 + 1) < arr.length) {//向左递归遍历
postList(2 * index + 1);
}
if ((index * 2 + 2) < arr.length) {//向右递归遍历
postList(2 * index + 2);
}
System.out.println(arr[index]);//输出当前元素
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战