我想创建一个递归方法,该方法可以复制树并将其作为树而不是节点返回。这是结构:
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;
}
}}
答案 0 :(得分:1)
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;
}