当前位置:网站首页>顺序二叉树---实现数组的二叉树前序遍历输出
顺序二叉树---实现数组的二叉树前序遍历输出
2022-07-30 05:46:00 【RSDYS】
特点:
1.顺序二叉树只考虑完全二叉树
2.第n个元素的左子节点为2*n+1
3.第n个元素的右子节点为2*n+2
4.第n个元素的父节点为(n-1)/2
代码:
/*
* 给你一个数组,要求以二叉树前序遍历的方式进行遍历
* */
public class ArrayBinaryTreeDemo {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4 , 5, 6, 7};
ArrBinaryTree arrBinaryTree = new ArrBinaryTree(arr);
arrBinaryTree.preOrder(0);
}
}
//顺序二叉树
class ArrBinaryTree{
private int[] arr; //存储数据节点的数组
public ArrBinaryTree(int[] arr){
this.arr = arr;
}
//重载
public void preOrder(){
this.preOrder(0);
}
//完成前序遍历
/* index 为数组下标
* */
public void preOrder(int index){
//如果数组为空,或者arr.length = 0;
if(arr == null || arr.length == 0){
System.out.println("数组为空,不能按照二叉树前序遍历");
}
//输出当前这个元素
System.out.println(arr[index]);
//向左递归遍历
if((index * 2 + 1) < arr.length){
preOrder(2 * index + 1);
}
if((index * 2 + 2) < arr.length){
preOrder(2 * index + 2);
}
}
}边栏推荐
- 闭包(你不知道的JS)
- About map custom sorting of keys
- QT serial and CAN dynamic real-time display the log data
- Difference between logical shift right and arithmetic right shift
- [Punctuality Atom] Simple application of sys.c, sys.h bit-band operations
- QT weekly skills (2)~~~~~~~~~ interface buttons
- vscode 设置 sublime 的主题
- VsCode连接远程服务器并修改文件代码
- Written before the official account - QT, ARM, DSP, microcontroller, power electronics and transmission!
- 2021 soft exam intermediate pass
猜你喜欢
随机推荐
About map custom sorting of keys
多层板的层数,为啥选项都是偶数?就不能选奇数?
自定义类加载器
昆仑通态屏幕制作(连载1)---接触篇
Kunlun state screen production (serial 3) - based article (button serial port to send)
NS3报错 fatal error: ns3/opengym-module.h: No such file or directory
如何开发出成功的硬件产品,一个产品由概念的产生到产品的落地量产又需要经历哪些流程呢?
Cannnot download sources不能下载源码百分百超详细解决方案
PCB 一分钟科普之你真的懂多层板吗?
服务器基础知识:包含基本概念,作用,服务器选择,服务器管理等(学习来自米拓建站)
使用Dva项目作Antd的Demo
表格比手机屏幕宽时不压缩,可左右滚动,格子内容不换行
写在公众号之前——QT,ARM,DSP,单片机,电力电子与传动!
Kunlun State Screen Production (serialization 4) --- Basics (graphical setting and display, button lights)
Insertion Sort in Classic Sort
Acwing刷题第一节
QT serial 3: LORA test platform based on QT and STM32H750 (2)
this的指向问题
动态规划入门 JS
查看 word版本号









