JAVA实现将数组存入二叉树中
来源:互联网 发布:base64 js 编辑:程序博客网 时间:2024/06/07 09:44
在工作中,当我们面临在使用内存存储数据的时候,只使用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)); }}执行结果:
0 0
- JAVA实现将数组存入二叉树中
- JAVA创建二叉树将数组中的数依次存入二叉树,并分别用先序,后序,中序遍历;
- 中序遍历二叉树将遍历结果存入双向循环链表C语言实现
- Java导入Excel表格,并将数据存入数组中
- PHP将数组存入到数据库中
- PHP将数组存入到数据库中
- java 将图片存入mysql数据库中
- java 将数组转化为 二叉树
- Java--实现一个数组去掉含有的0元素后,存入一个新的数组中
- 将TXT文档中数据存入数组中 C#
- n个整数存入一维数组中,将该数组循环移动m位,用指针实现。
- 使用adatabase将打开的数据库名称存入数组中
- 将字符串中的每一个字符存入数组中
- 怎么将ListBox中的数据全部存入一个数组中
- 将整型数值存入到byte数组中
- matlab读取txt,将特定行中数字存入数组
- Java 键盘输入数字(空格隔开) 将数字存入数组。
- 将ASCall码存入数组
- spring框架学习(三)junit单元测试
- 如何将Eclipse中的项目迁移到Android Studio 中
- 基础备忘:C++编译期多态与运行期多态
- linux命令 at
- Android 启动程序时,进入的动态效果
- JAVA实现将数组存入二叉树中
- Ambiguous handler methods mapped for HTTP path 'http://localhost:8080/runyu/a/res/resource': {public
- spring框架学习(四)自动装配
- Scala 异常处理
- 使用Ruby DBI模块
- 线程与进程
- 欢迎使用CSDN-markdown编辑器
- linux命令crontab
- 如何正确选择云服务?|创业公司做产品的感想