Java 将后序遍历值放入arraylist中
在web上有打印值的解决方案,如下所示:Java 将后序遍历值放入arraylist中,java,recursion,arraylist,Java,Recursion,Arraylist,在web上有打印值的解决方案,如下所示: 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 dea
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
,但我的困难是我想返回它,所以我的返回类型将是ArrayList
。问题是我不知道在基本情况下返回什么:
if (node == null)
return;
我的方法返回一个
ArrayList
,那么对于上面的基本情况,我可以返回什么呢?在结束情况下,您可以返回一个空列表,并通过调用addAll
来累积结果:
List getPostOrderList(节点节点){
List retVale=new ArrayList();
if(node==null){
返回返回;
}
//左子树上的第一次递归
addAll(getPostOrderList(node.left));
//然后在右子树上重现
addAll(getPostOrderList(node.right));
//现在处理节点
retVal.add(节点);
返回返回;
}
谢谢,非常有用