如何深拷贝二叉树?

新手上路,请多包涵

我想使用我自己的 Node 类在 Java 中实现树结构。但是我很困惑如何做一个深拷贝来复制一棵树。

我的节点类将是这样的:

 public class Node{
private String value;
private Node leftChild;
private Node rightChild;
....

我是递归的新手,有没有我可以学习的代码?谢谢!

原文由 lkkeepmoving 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

尝试

class Node {
    private String value;
    private Node left;
    private Node right;

    public Node(String value, Node left, Node right) {
        this.value = value;
        ...
    }

    Node copy() {
        Node left = null;
        Node right = null;
        if (this.left != null) {
            left = this.left.copy();
        }
        if (this.right != null) {
            right = this.right.copy();
        }
        return new Node(value, left, right);
    }
}

原文由 Evgeniy Dorofeev 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用预序遍历递归地进行。

     public static Node CopyTheTree(Node root)
    {
        if (root == null)
        {
            return null;
        }
        Node newNode = new Node(null, null, root.Value);
        newNode.Left= CopyTheTree(root.Left);
        newNode.Right= CopyTheTree(root.Right);
        return newNode;
    }

原文由 aerin 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题