【问题标题】:Put the post-order traversal values in an arraylist将后序遍历值放入数组列表中
【发布时间】:2020-12-07 10:25:02
【问题描述】:

在网络上有打印值的解决方案,如下所示:

void printPostorder(Node node) 
{ 
    if (node == null) 
        return; 

    // first recur on left subtree 
    printPostorder(node.left); 

    // then recur on right subtree 
    printPostorder(node.right); 

    // now deal with the node 
    System.out.print(node.key + " "); 
}

但我的问题是我不想打印这些值,而是将它们放在ArrayList 中。这部分很简单我尝试使用ArrayList.add 而不是System.out.print,但我的困难是我想返回它,所以我的返回类型将是void 而不是ArrayList。问题是我不知道在基本情况下要返回什么:

if (node == null) 
        return;

我的方法确实返回了 ArrayList,那么对于上述基本情况,我可以返回什么?

【问题讨论】:

    标签: java recursion arraylist


    【解决方案1】:

    在最终情况下,您可以返回一个空列表,并通过调用 addAll 来累积结果:

    List<Node> getPostOrderList(Node node) { 
        List<Node> retVale = new ArrayList<>();
        if (node == null) {
            return retVal; 
        }
    
        // first recur on left subtree 
        retVal.addAll(getPostOrderList(node.left));
    
        // then recur on right subtree 
        retVal.addAll(getPostOrderList(node.right));
    
        // now deal with the node 
        retVal.add(node);
    
        return retVal;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-30
      • 1970-01-01
      • 1970-01-01
      • 2018-01-25
      • 1970-01-01
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多