自学内容网 自学内容网

尚硅谷Java数据结构--顺序存储二叉树(前中后序遍历)

package DataStructure;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86178
 * Date: 2024-03-05
 * Time: 9:55
 */
public class ArrBinaryTreeDemo {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7};
        int[] brr = {};//空数组
        ArrBinaryTree tree = new ArrBinaryTree(arr);
        //tree.preOrder();
        tree.infixOrder();
        tree.postOrder();
    }
}

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) {
            throw new RuntimeException("数组为空,无法进行遍历");
        }
        System.out.print(arr[index] + " ");//打印父节点
        if (index == arr.length - 1) return;
        if (2 * index + 1 < arr.length) preOrder(2 * index + 1);
        if (2 * index + 2 < arr.length) preOrder(index * 2 + 2);
    }

    public void infixOrder(int index) {
        if (arr == null || arr.length == 0) {
            throw new RuntimeException("数组为空,无法进行遍历");
        }
        if (2 * index + 1 < arr.length) infixOrder(2 * index + 1);

        System.out.print(arr[index] + " ");//打印父节点
        if (index == arr.length - 1) return;

        if (2 * index + 2 < arr.length) infixOrder(index * 2 + 2);
    }

    public void postOrder(int index) {
        if (arr == null || arr.length == 0) {
            throw new RuntimeException("数组为空,无法进行遍历");
        }
        if (2 * index + 1 < arr.length) postOrder(2 * index + 1);

        if (2 * index + 2 < arr.length) postOrder(index * 2 + 2);
        System.out.print(arr[index] + " ");//打印父节点
        if (index == arr.length - 1) return;
    }
}

原文地址:https://blog.csdn.net/m0_70094411/article/details/136470075

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!