在Java中,如何将二叉树存储到二维数组中并打印出来? [英] How to store a binary search tree into a two-d array and print it out, in Java?

查看:54
本文介绍了在Java中,如何将二叉树存储到二维数组中并打印出来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个二叉树,但我不知道如何将它放入二维数组(我对递归和非递归都感兴趣)并将其打印出来。

如下图

           7
         /   
        5     9
       /    / 
      4   6 8  15
      .
      .
      .

很抱歉我的表达含糊不清。基本上我是想试着 1)从文件中读取数字序列并为其构建二叉搜索树。

2)我需要将树绘制到字符数组中(必须是二维数组)来表示绘图区域。因此,树的根必须位于数组第一行的中间,第一个左子对象必须位于第二行的一半的中间,第一个右子对象必须位于第二行的另一个半部分的中间。以此类推。

如下图

------------34------------

-----24------------56-----

---9-----32-----41----57--
3)最后,我需要将其打印出来(作为第一个图形)。

我有BinaryNode.class BinaryTree.class,并且在tree类中, 根、左子和右子有几个基本方法getmethod和setmethod。

以下是我在Main类上的部分代码:

BinaryTree BinarySearchTree = new BinaryTree();

 FileReader theFile;

 BufferedReader inFile;

 String oneLine;

 try{

   theFile = new FileReader(args[0]);

   inFile = new BufferedReader(theFile);

   while((oneLine = inFile.readLine())!= null){

    String[] list = oneLine.split(",");

    for(int i=0; i<list.length; i++){                           

      BinaryNode TreeNode = new BinaryNode(list[i]);

      BinaryTree.insert(BinarySearchTree, TreeNode.element);

      }

      }

      }

      catch (Exception e) {

           System.out.println(e);

          }


    // building binary search tree

    public static BinaryTree insert(BinaryTree t, Object x){

      if(t.isEmpty())

      return new BinaryTree(x);

      else{

          if(((Integer)t.getRootobj()).intValue()<((Integer)x).intValue())

            t.setRight(insert(t.getRight(),x));

          else

            t.setLeft(insert(t.getLeft(),x));

            return t;

         }

推荐答案

您可以在第一个数组中使用节点的值作为索引,在第二个数组中使用要存储的子数组的值。可以将左子对象的值作为索引0,将右子对象的值放在索引1中。要标记没有左子对象或右子对象,可以使用负值或零。要知道初始的根元素,可以搜索具有至少一个元素的数组的第一个元素,也可以想办法将根元素存储在某个地方。肯定不是最佳选择,但应该可行。

示例如下:

[0] -> {0,0}
[1] -> {2,3}
[2] -> {4,5}
[3] -> {6,7}
[4] -> {0,0}

这篇关于在Java中,如何将二叉树存储到二维数组中并打印出来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆