JAVA实现将数组存入二叉树中

当面临内存限制时,可以使用自定义数据结构如二叉树来存储数据,以避免HashMap的不断扩容。本文以Java为例,介绍如何将数组存储到二叉树中,提供了一个简单的实现示例,适用于基础的存储需求,更复杂的需求可自行扩展。

在工作中,当我们面临在使用内存存储数据的时候,只使用hashmap存储,可能会面临内存不足,只能不断扩容的情况下。于是我们可以自己写一些数据结构来存储,譬如二叉树这样的数据结构来存储,这样如果重复的字段只存在一个节点,不同的字段只需要延时叶子节点即可。

下面一起来看看,如何用java实现二叉树的存储结构,下面只是一个简单的例子,如果读者需要使用复杂的结构的话,可以按自己的需要自行实现;


啥也不说了,上代码:

package Tree;


import java.util.ArrayList;
import java.util.List;

/**
 * Created by ykanghe on 2016/9/7.
 */
public class BinTree {

    private int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    private static List<Node> nodeLIst = new ArrayList<Node>();

    private static class Node {
        Node leftChild;
        Node rightChidl;
        int data;

        Node(int data) {
            this.data = data;
        }
    }

    public void createBintree() {
        for (int i = 0; i < array.length; i++) {
            nodeLIst.add(new Node(array[i]));
        }

        if (nodeLIst.size() > 0) {
            for (int y = 0; y < array.length / 2 - 1; y++) {
                //leftChild
                if (null != nodeLIst.get(2 * y + 1)) {
                    nodeLIst.get(y).leftChild = nodeLIst.get(2 * y + 1);
                }
                //rightChild
                if (null != nodeLIst.get(2 * y + 2)) {
                    nodeLIst.get(y).rightChidl = nodeLIst.get(2 * y + 2);
                }
            }
            //最后一个父节点不一定有孩子
            int lastParentIndex = array.length / 2 - 1;
            // 左孩子
            nodeLIst.get(lastParentIndex).leftChild = nodeLIst
                    .get(lastParentIndex * 2 + 1);
            //奇数时候有右孩子
            if (array.length % 2 == 1) {
                nodeLIst.get(lastParentIndex).rightChidl = nodeLIst
                        .get(lastParentIndex * 2 + 2);
            }
        }
    }

    /**
     * 先序遍历
     *
     * @param node
     */
    public static void preOrderTraver(Node node) {
        if (null != node) {
            System.out.println("node:" + node.data);
            preOrderTraver(node.leftChild);
            preOrderTraver(node.rightChidl);
        } else {
            return;
        }
    }

    public static void main(String[] args) {
        BinTree tree = new BinTree();
        tree.createBintree();
        preOrderTraver(nodeLIst.get(0));
    }

}
执行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值