Java--算法--顺序存储二叉树
- 顺序存储二叉树的介绍:
-
顺序存储二叉树的代码实现:
-
-
-
package com.model.tree; /** * @Description:测试类 * @Author: 张紫韩 * @Crete 2021/7/14 9:03 * 演示顺序存储二叉树 */ public class TreeDemo02 { public static void main(String[] args) { int[] array={1,2,3,4,5,6,7}; ArrayBinaryTree tree = new ArrayBinaryTree(array); tree.preOrder(); System.out.println("---------------------"); tree.infixOrder(); } } class ArrayBinaryTree{ private int[] array; public ArrayBinaryTree(int[] array) { this.array = array; } public void preOrder(){ preOrder(0); } public void infixOrder(){ infixOrder(0); } // 前序遍历二叉树 public void preOrder(int index){ if (array.length==0){ System.out.println("数组为空,不能按照二叉树的前序遍历"); }else { System.out.println(array[index]); if (index*2+1< array.length){ preOrder(2*index+1); } if (index*2+2< array.length){ preOrder(2*index+2); } } } public void infixOrder(int index){ if (array.length==0){ System.out.println("数组为空,不能按照二叉树的前序遍历"); }else { if (index*2+1< array.length){ preOrder(2*index+1); } System.out.println(array[index]); if (index*2+2< array.length){ preOrder(2*index+2); } } } }
-