Search code examples
javarecursiontreetreenode

How to deep copy a Binary Tree?


I would like using my own Node class to implement tree structure in Java. But I'm confused how to do a deep copy to copy a tree.

My Node class would be like this:

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

I'm new to recursion, so is there any code I can study? Thank you!


Solution

  • try

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