如何深度复制二叉树?

lkk*_*ing 8 java tree recursion treenode

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

我的Node类是这样的:

public class Node{
private String value;
private Node leftChild;
private Node rightChild;
....
Run Code Online (Sandbox Code Playgroud)

我是递归的新手,所以我可以学习任何代码吗?谢谢!

Evg*_*eev 23

尝试

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);
    }
}
Run Code Online (Sandbox Code Playgroud)


Aer*_*rin 6

使用前序遍历递归地执行此操作。

    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;
    }
Run Code Online (Sandbox Code Playgroud)