顺序存储二叉树
介绍
从数据存储来看,数组存储方式和树的存储方式可以相互转换,即数组可以转换成树,树也可以转换成数组,如图:
要求:
- 上图的二叉树的节点,要求以数组的方式来存放 arr:[1,2,3,4,5,6,7]
- 要求在遍历数组arr 时,仍然可以以前序遍历、中序遍历、后序遍历的方式完成节点的遍历
顺序存储二叉树的特点
- 顺序二叉树通常只考虑完全二叉树
- 第n个元素的左子节点为2*n+1
- 第n个元素的右子节点为2*n+2
- 第n个元素的父节点为 (n-1)/2
- n:表示二叉树中的第几个元素(按0开始编号)
代码实现
package com.tmo.tree;
/**
* 顺序存储二叉树
* @author tmo
*
*/
public class ArrayBinaryTreeDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {1,2,3,4,5,6,7};
ArrayBinaryTree arrayBinaryTree = new ArrayBinaryTree(arr);
System.out.println("前序遍历");
arrayBinaryTree.preOrder(0);
}
}
class ArrayBinaryTree{
private int[] arrayBinaryTree;
public ArrayBinaryTree(int[] arrayBinaryTree) {
super();
this.arrayBinaryTree = arrayBinaryTree;
}
//前序遍历
public void preOrder(int index) {
//判断数组为空,不进行遍历
if (arrayBinaryTree == null || arrayBinaryTree.length == 0) {
System.out.println("数组为空,不能按照二叉树进行前序遍历");
}
//输出当前的元素
System.out.print(arrayBinaryTree[index]+" ");
//向左递归查找
if ((index * 2 + 1) < arrayBinaryTree.length) {
preOrder(index * 2 + 1);
}
//向右递归查找
if ((index * 2 + 2) < arrayBinaryTree.length) {
preOrder(index * 2 + 2);
}
}
}