Java数据结构——顺序存储二叉树

二叉树的顺序存储,指的是使用顺序表(数组)存储二叉树。需要注意的是,顺序存储只适用于完全二叉树。换句话说,只有完全二叉树才可以使用顺序表存储。

对于将数组转为二叉树,有以下特点:

设数组索引为n,左子节点处的索引为2*n+1,右子节点索引为2*n+2,父节点索引为(n-1)/2。

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7};
        ArrBinaryTree tree = new ArrBinaryTree(arr);
        System.out.println("前序遍历结果为:");
        tree.preOrder(0);
        System.out.println();
        System.out.println("中序遍历结果为:");
        tree.infixOrder(0);
        System.out.println();
        System.out.println("后序遍历结果为:");
        tree.postOrder(0);
        System.out.println();
    }
}

//顺序存储二叉树
class ArrBinaryTree {
    private int[] arr;

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

    //前序遍历
    public void preOrder(int index) {
        if (this.arr == null || this.arr.length == 0) {
            System.out.println("数组为空,无法构建二叉树");
            return;
        }
        System.out.print(arr[index] + " ");
        //遍历左子树
        if ((index * 2 + 1) < this.arr.length) {
            preOrder((index * 2 + 1));
        }
        //遍历右子树
        if ((index * 2 + 2) < this.arr.length) {
            preOrder((index * 2 + 2));
        }
    }

    //中序遍历
    public void infixOrder(int index) {
        if (this.arr == null || this.arr.length == 0) {
            System.out.println("数组为空,无法构建二叉树");
            return;
        }
        //遍历左子树
        if ((index * 2 + 1) < this.arr.length) {
            infixOrder((index * 2 + 1));
        }
        System.out.print(arr[index] + " ");
        //遍历右子树
        if ((index * 2 + 2) < this.arr.length) {
            infixOrder((index * 2 + 2));
        }
    }

    //后序遍历
    public void postOrder(int index) {
        if (this.arr == null || this.arr.length == 0) {
            System.out.println("数组为空,无法构建二叉树");
            return;
        }
        //遍历左子树
        if ((index * 2 + 1) < this.arr.length) {
            postOrder((index * 2 + 1));
        }
        //遍历右子树
        if ((index * 2 + 2) < this.arr.length) {
            postOrder((index * 2 + 2));
        }
        System.out.print(arr[index] + " ");
    }

}
前序遍历结果为:
1 2 4 5 3 6 7 
中序遍历结果为:
4 2 5 1 6 3 7 
后序遍历结果为:
4 5 2 6 7 3 1 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值