java实现数组顺序存储二叉树遍历

java实现数组顺序存储二叉树遍历

二叉树类

class ArrBinaryTree {
    private int[] arr;

    public ArrBinaryTree(int[] arr) {
        this.arr = arr;
    }


    /**
     * 重载,方便使用
     */
    public void preOrder() {
        this.preOrder(0);
    }

    public void infixOrder() {
        this.infixOrder(0);
    }

    public void postOrder() {
        this.postOrder(0);
    }

    /**
     * 前序遍历
     */
    public void preOrder(int index) {
        if (arr == null || arr.length == 0) {
            System.out.println("数组为空");
        }
        System.out.println(arr[index]);
        // 向左递归
        if ((index * 2 + 1) < arr.length) {
            preOrder(index * 2 + 1);
        }
        // 向右递归
        if ((index * 2 + 2) < arr.length) {
            preOrder(index * 2 + 2);
        }
    }

    /**
     * 中序遍历
     */
    public void infixOrder(int index) {
        if (arr == null || arr.length == 0) {
            System.out.println("数组为空");
        }
        // 向左递归
        if ((index * 2 + 1) < arr.length) {
            preOrder(index * 2 + 1);
        }
        System.out.println(arr[index]);
        // 向右递归
        if ((index * 2 + 2) < arr.length) {
            preOrder(index * 2 + 2);
        }
    }

    /**
     * 后序遍历
     */
    public void postOrder(int index) {
        if (arr == null || arr.length == 0) {
            System.out.println("数组为空");
        }
        // 向左递归
        if ((index * 2 + 1) < arr.length) {
            preOrder(index * 2 + 1);
        }
        // 向右递归
        if ((index * 2 + 2) < arr.length) {
            preOrder(index * 2 + 2);
        }
        System.out.println(arr[index]);
    }
}

测试类

/**
 * 数组顺序存储二叉树的遍历
 */
public class SequentialStorage {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7};
        ArrBinaryTree arrBinaryTree = new ArrBinaryTree(arr);

        System.out.println("前序遍历");
        arrBinaryTree.preOrder();
        System.out.println("=========");

        System.out.println("中序遍历");
        arrBinaryTree.infixOrder();
        System.out.println("=========");

        System.out.println("后序遍历");
        arrBinaryTree.postOrder();
        System.out.println("=========");

    }
}
posted @ 2022-04-18 16:16  CoderCatIce  阅读(81)  评论(0编辑  收藏  举报