如何防止我的索引在java中的递归函数中重置?

时间:2013-03-26 06:51:36

标签: java indexing

我试图将我的二叉树插入到一个数组中,在函数中有一个递归循环,当它重新启动我的索引时会重置并且我在数组中以错误的顺序输入值。 该指数在主要国家已被确定。

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]);
    }
    }

}

1 个答案:

答案 0 :(得分:0)

您遇到的问题是,在执行第一次递归调用toArray(_root.ls, arr,i);后,i的值不会更改,但会保持不变。这是因为整数在递归中通过值传递,然后在调用返回后,本地i将不会更改。解决此问题的一种方法是使函数toArray返回一个int - 函数返回时i的值。您似乎使用布尔返回值来指示给定的子树是否为空。我相信你将不再需要它。

代码类似于:

public boolean  toArray (Node _root, String[] arr, int i)
{
  if (_root == null)
  {
    return i;
  }
  if (_root.isleaf())
  {
    arr[i]=this.data;
    i++;
    if (this.father == null)
        return i;
    else if (this.father.ls==this)
    {
        this.father.ls = null;
        return i;
    }
    else 
    {
        this.father.rs=null;
        return i;
    }
  }
  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;
  }
  i = toArray(_root.ls, arr,i);
  i = toArray(_root.rs, arr,i);
  if (this.data !=null)
  {
    arr[i] = this.data;
    i++;
    this.data = null;
    _root.data=null;
  }
  return i;
}