I am trying to copy a binary tree using the pre order traversal but I am stuck. As I am not putting any of the values into a new tree they are obviously not copying correctly...
public class Node{
int key;
String name;
Node leftChild;
Node rightChild;
Node(int key, String name){
this.key = key;
this.name = name;
}
public class BinaryTree{
public Node root;
public void copyTree(Node focusNode){
if(focusNode != null){
Node copyNode = new Node(focusNode.key, focusNode.name);
//System.out.println(copyNode);
copyTree(focusNode.leftChild);
copyTree(focusNode.rightChild);
}
}
}
Here's one solution. I added a toString()
method to the Node
class for presentation purposes.
class Node {
int key;
String name;
Node leftChild;
Node rightChild;
Node(int key, String name) {
this.key = key;
this.name = name;
}
public String toString() {
return "[" + key + "," + name + "]";
}
}
The BinaryTree
was slightly modified as well:
class BinaryTree {
public Node root;
public BinaryTree copyTree(Node focusNode) {
BinaryTree bt = new BinaryTree();
bt.root = preOrderCopy(focusNode);
return bt;
}
public static void preOrderPrint(BinaryTree t) {
preOrderPrint(t.root);
}
public static void preOrderPrint(Node n) {
if (n == null) {
// base case
return;
}
System.out.println(n);
preOrderPrint(n.leftChild);
preOrderPrint(n.rightChild);
}
private Node preOrderCopy(Node focusNode) {
if (focusNode == null) {
// base case
return null;
}
Node copy = new Node(focusNode.key, focusNode.name);
copy.leftChild = preOrderCopy(focusNode.leftChild);
copy.rightChild = preOrderCopy(focusNode.rightChild);
return copy;
}
}
To test the code, I created a BinaryTree
based on the one shown on the Wikipedia page for Tree Traversal. Here's a picture of the tree used in this example:
The proper Pre-order traversal for this example is : F, B, A, D, C, E, G, I, H
. You can use the following code to test this implementation:
public class NodeTest {
public static void main(String[] args) {
BinaryTree bt = new BinaryTree();
Node a = new Node(1, "A");
Node b = new Node(2, "B");
Node c = new Node(3, "C");
Node d = new Node(4, "D");
Node e = new Node(5, "E");
Node f = new Node(6, "F");
Node g = new Node(7, "G");
Node h = new Node(8, "H");
Node i = new Node(9, "I");
f.leftChild = b;
b.leftChild = a;
b.rightChild = d;
d.leftChild = c;
d.rightChild = e;
f.rightChild = g;
g.rightChild = i;
i.leftChild = h;
bt.root = f;
System.out.println("Print full tree:");
BinaryTree.preOrderPrint(bt.copyTree(f));
System.out.println("Only print f's left sub-tree:");
BinaryTree.preOrderPrint(bt.copyTree(f.leftChild));
}
}
Running the above code produces the following output:
Print full tree:
[6,F]
[2,B]
[1,A]
[4,D]
[3,C]
[5,E]
[7,G]
[9,I]
[8,H]
Only print f's left sub-tree:
[2,B]
[1,A]
[4,D]
[3,C]
[5,E]