2015-12-14 44 views
1

我试图把一个二叉搜索树与n个元素并将它们存储在一个数组列表中。目前,它们存储在数组列表中的位置是以树的根为元素1(p =数组中父元素的索引),左边的子元素为索引p * 2,右边的子元素为在指数p * 2 + 1。在一个数组列表中存储一个二叉搜索树

目前我尽量不这样做使用此代码:

public static void arraywriter(TreeNode<String> node) throws FileNotFoundException 
{ 
    int pos = 1; 
    outputform.set(pos, node.getElement()); 
    pos = pos*2; 
    if(node.getLeft() != null) { 
     arraywriter(node.getLeft()); 
    } 
    pos = pos+1; 
    if(node.getRight() != null) { 
     arraywriter(node.getRight()); 
    } 
} 

请告诉我错了我的逻辑是什么?我将如何完成这项工作? 当前如果我使用这个,然后尝试打印输出内容(这是ArrayList的名称,它的基本大小为10,000)我得到:索引之一返回为空,其余为“n”其中也是我初始化每一个元素。

谢谢!

+2

的一个问题是,你pos'目前设定'1',在这样arraywriter'其价值开始将每次1。您可能希望将'pos'作为参数添加到'arraywriter'中,以便可以使用'pos * 2'和'pos * 2 + 1'来调用它,然后您将首次调用'arraywriter', pos' of 1. – mikej

+1

嘿谢谢!我不相信我错过了! – TheJavaKing

回答

0

您总是对pos使用固定值1,这意味着您一次又一次地覆盖它。

考虑使用类似这样:

public static void arraywriter(TreeNode<String> node, int pos) throws FileNotFoundException 
{ 
    outputform.set(pos, node.getElement()); 
    pos = pos*2; 
    if(node.getLeft() != null) { 
     arraywriter(node.getLeft(), pos); 
    } 
    pos = pos+1; 
    if(node.getRight() != null) { 
     arraywriter(node.getRight(), pos); 
    } 
}