如何通过Java中的递归返回值列表? [英] How to return a list of values through recursion in java?

查看:1230
本文介绍了如何通过Java中的递归返回值列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过递归返回单个值就可以了.但是,如果我想返回值列表,那么每次调用都会递归进行.这是我的代码.

Returning a single value through recursion works just fine. But what if I want to return a list of values that recursion goes through each call. Here's my code.

public void inOrder(Node focusNode) {

  /* ArrayList<Integer> tempList = new ArrayList<Integer>(); */

  if ( focusNode != null) {

    inOrder(focusNode.getLeftNode());
    System.out.println(focusNode);
    /*  tempList.add(focusNode.getElement()); */
    inOrder(focusNode.getRightNode());

  }

/*  int[] elems = new int[tempList.toArray().length];
  int i = 0;
  for ( Object o : tempList.toArray()) 
    elems[i++] = Integer.parseInt(o.toString()); */

  //return tempList;
}

遍历时打印值会得到预期的输出.但是存储这些值是行不通的.它仅在列表中返回单个值.有人可以帮我吗?

printing values while traversing through gives the expected output. But storing those values is not working. It only returns with a single value in a list. Can someone help me with this?

推荐答案

为什么不将引用数组和起始节点一起传递给数组列表? inOrder方法运行后,您将获得一系列有序的值,可以根据需要使用它们.

Why don't you just pass in a reference to an array list along with your starting node? After your inOrder method runs, you'll have an ordered series of values that you can use as you please.

// method signature changed
public void inOrder(Node focusNode, ArrayList vals) {

    /* ArrayList<Integer> tempList = new ArrayList<Integer>(); */

    if ( focusNode != null) {
        // args changed here
        inOrder(focusNode.getLeftNode(), vals);
        // adding node to array list rather than dumping to console
        vals.add(focusNode);
    /*  tempList.add(focusNode.getElement()); */
        inOrder(focusNode.getRightNode());
}

这篇关于如何通过Java中的递归返回值列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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