am trying to understand how clone working with the tree, so I wanted to make a tree that The input and output will be the same tree (that is, the same values in the nodes, the nodes are connected in the same way), but it must consist of different objects so as I understand the clone concept I tried to do that here is my code for better understand;
class Node {
public int val;
int key;
Node left, right;
public Node(int data){
key = data;
left = right = null;
}
}
class binaryTree {
Node root;
binaryTree() {
root = null;
}
void preOrder(Node node) {
if (node == null)
return;
System.out.print(node.key + " ");
preOrder(node.left);
preOrder(node.right);
}
void preOrder_traversal() {
preOrder(root);
}
public Node cloneTree(Node root) {
if (root == null) return null;
Node newNode = new Node(root.val);
newNode.left = cloneTree(root.left);
newNode.right = cloneTree(root.right);
return newNode;
}
}
this the main class
public class Main {
public static void main(String[] args) {
binaryTree tree = new binaryTree();
/* 45
// \\
10 90
// \\
7 12 */
tree.root = new Node(45);
tree.root.left = new Node(10);
tree.root.right = new Node(90);
tree.root.left.left = new Node(7);
tree.root.left.right = new Node(12);
// Traversal
System.out.println(" \t\t 45\n" +
" // \\\\\n" +
" 10 90\n" +
" // \\\\\n" +
" 7 12 :");
System.out.print(" \t \t\t" );
tree.preOrder_traversal();
System.out.println();
tree.cloneTree(tree.root);
System.out.print(" \t \t\t" );
tree.preOrder_traversal();
}
}
output
45 // \ 10 90 // \ 7 12 : 45 10 7 12 90 45 10 7 12 90
in the cloneTree() function I tried to make a new object from the Node class; is the right way to make an object form the tree or the is a better way