java – 如何将Node树的数据转换为有序的ArrayList?

public class Node {
private int data;

public int getData() {
    return data;
}

private Node left;
private Node right;

public Node(int d, Node l, Node r) {
    data = d;
    left = l;
    right = r;
}

// Deep copy constructor
public Node(Node o) {
    if (o == null) return;
    this.data = o.data;
    if (o.left != null) this.left = new Node(o.left);
    if (o.right != null) this.right = new Node(o.right);
}

public List<Integer> toList() {
// Recursive code here that returns an ordered list of the nodes
}

全班在这里:https://pastebin.com/nHwXMVrd

我可以使用什么递归解决方案返回Node内部整数的有序ArrayList?我已经尝试了很多东西但是我一直难以找到递归解决方案.

最佳答案 我不是在Java中表现出色,但这是做这件事的一般想法:

public List<Integer> toList() 
{
   List<Integer> newList = new List<Integer>();
   newList.add(this.data);
   if(left != null)
      newList.addAll(left.toList());
   if(right != null)
      newList.addAll(right.toList());
   return newList;
}
点赞