package Tree;public class ArrayBinaryDemo { public static void main(String[] args) { int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7}; ArrayBinarTree arrayBinarTree = new ArrayBinarTree(arr); arrayBinarTree.preOrder(); System.out.println(); arrayBinarTree.infixOrder(); System.out.println(); arrayBinarTree.postOrder(); }}//编写一个ArrayBinaryTree,实现顺序存储二叉树class ArrayBinarTree { private int[] arr;//存储数据节点 public ArrayBinarTree(int[] arr) { this.arr = arr; } public void preOrder(){ this.preOrder(0); } public void infixOrder(){ this.infixOrder(0); } public void postOrder(){ this.postOrder(0); } //编写一个方法.完成顺序存储二叉树的一个前序遍历 //index表示数组的下标 public void preOrder(int index) { //若果数组为空,或者arr.length = 0 if (arr.length == 0 || arr == null) { System.out.println("数组为空,不能按照二叉树前序遍历"); } //输出当前这个元素 System.out.print(arr[index] + " "); //左递归 if (2 * index + 1 < arr.length) { preOrder(2 * index + 1); } //右递归 if (2 * index + 2 < arr.length) { preOrder(2 * index + 2); } } public void infixOrder(int index) { //若果数组为空,或者arr.length = 0 if (arr.length == 0 || arr == null) { System.out.println("数组为空,不能按照二叉树前序遍历"); } //左递归 if (2 * index + 1 < arr.length) { infixOrder(2 * index + 1); } System.out.print(arr[index] + " "); //右递归 if (2 * index + 2 < arr.length) { infixOrder(2 * index + 2); } } public void postOrder(int index) { //若果数组为空,或者arr.length = 0 if (arr.length == 0 || arr == null) { System.out.println("数组为空,不能按照二叉树前序遍历"); } //左递归 if (2 * index + 1 < arr.length) { postOrder(2 * index + 1); } //右递归 if (2 * index + 2 < arr.length) { postOrder(2 * index + 2); } //输出当前这个元素 System.out.print(arr[index] + " "); }}
顺序存储二叉树(Java代码实现)
时间:2023-06-08
相关推荐