首页 > 解决方案 > 复制没有父引用的树

问题描述

我想创建一个递归方法,它可以复制树并将其作为树而不是节点返回。这是结构:

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;
    }
}}

标签: java

解决方案


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;
}

推荐阅读