バイナリ ツリーを配列に挿入しようとしていますが、関数に recursiv ループがあり、インデックスを再起動するとリセットされ、値が間違った順序で配列に入力されます。インデックスはメインで初期化されます。
public boolean toArray (Node _root, String[] arr, int i)
{
if (_root == null)
{
return false;
}
if (_root.isleaf())
{
arr[i]=this.data;
i++;
if (this.father == null)
return false;
else if (this.father.ls==this)
{
this.father.ls = null;
return false;
}
else
{
this.father.rs=null;
return true;
}
}
if (_root.ls ==null)
{
arr[i] = _root.data;
i++;
_root.data=null;
}
if ( _root.ls!=null && _root.ls.isleaf() )
{
arr[i] = _root.ls.data;
i++;
_root.ls = null;
arr[i]=_root.data;
i++;
}
if ( _root.rs!=null && _root.rs.isleaf())
{
arr[i]=_root.rs.data;
i++;
_root.rs = null;
}
toArray(_root.ls, arr,i);
toArray(_root.rs, arr,i);
if (this.data !=null)
{
arr[i] = this.data;
i++;
this.data = null;
_root.data=null;
}
else
return false;
return false;
}
これが私のメインクラスです
public class Test_Tree {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BT mytree = new BT();
mytree.in("11","","","");
mytree.in("2","","","");
mytree.in("810","","","");
mytree.in("17","","","");
mytree.in("845","","","");
mytree.in("10","","","");
mytree.in("1","","","");
String[] arr = new String[10];
Node myroot = new Node (mytree._root);
int i=0;
myroot.toArray(myroot, arr,i);
for (int j=0; j<arr.length;j++)
{
System.out.println(arr[j]);
}
}
}