Java 复制没有父引用的树
我想创建一个递归方法,它可以复制一棵树并将其作为树而不是节点返回。结构如下:Java 复制没有父引用的树,java,Java,我想创建一个递归方法,它可以复制一棵树并将其作为树而不是节点返回。结构如下: public class Tree { Node root; public Tree(Node root) this.root = root; } public static class Node { int key; Node left; Node right; public Node(int key, Node left, Node right) {
public class Tree {
Node root;
public Tree(Node root)
this.root = root;
}
public static class Node {
int key;
Node left;
Node right;
public Node(int key, Node left, Node right) {
this.key = key;
this.left = left;
this.right = right;
}
}}
public Tree copy() {
if(root == null)
return new Tree(null);
else {
return new Tree(copyRec(root));
}
}
private Node copyRec(Node node) {
if(node != null) {
Node curr = new Node(node.key, null, null);
curr.left = copyRec(node.left);
curr.right = copyRec(node.right);
return curr;
}
return null;
}