我试图将我的二叉树插入到数组中,函数中有一个递归循环,当它重新启动我的索引时,我的索引会被重置,并且我在数组中以错误的顺序输入值。该索引主要是inizilized。
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]);
}
}
}