Mirroring a binary tree - java

I am trying to find the mirror image of a binary tree. Here is what I do so far:
import treetoolbox.*;
public class MirrorTree extends BinaryTree<String> {
public MirrorTree(String key) {
this(null, key, null);
}
public MirrorTree(MirrorTree left, String key, MirrorTree right) {
this.key = key;
this.left = left;
this.right = right;
root = this;
}
public MirrorTree mirrorSymmetricTree() {
if (root == null) {
return null;
}
final MirrorTree left = (MirrorTree) root.left;
right = root.right;
root.left = mirrorSymmetricTree(right);
root.right = mirrorSymmetricTree(left);
return (MirrorTree) root;
}
public static MirrorTree mirrorSymmetricTree(BinaryTree<String> t) {
return null;
}
}
What am I doing wrong? The problem should be in this part:
if (root == null) {
return null;
}
final MirrorTree left = (MirrorTree) root.left;
right = root.right;
root.left = mirrorSymmetricTree(right);
root.right = mirrorSymmetricTree(left);
return (MirrorTree) root;
But I think I am missing something.

Delete this function:
public static MirrorTree mirrorSymmetricTree(BinaryTree<String> t) {
return null;
}
Add the parameter to this function to make it recursive:
public MirrorTree mirrorSymmetricTree(BinaryTree<String> t) {
if (root == null) {
return null;
}
final MirrorTree left = (MirrorTree) root.left;
right = root.right;
root.left = mirrorSymmetricTree(right);
root.right = mirrorSymmetricTree(left);
return (MirrorTree) root;
}

Your problem is here:
public static MirrorTree mirrorSymmetricTree(BinaryTree<String> t) {
return null;
}
you are not doing anything in this method!

Assuming you are using a BinaryTree<E> similiar to this documentation
You can see live version of my solution
This is how BinaryTree<E> is built where BinaryTree<E> is the Binary-Tree node itself, and every node in the tree is a tree by itself. This is how the insert method for BinaryTree<E> looks like
public void insert(T value)
{
if (this.value == null)
{
this.value = value;
return;
}
else
{
if (this.value.compareTo(value) >= 0)
{
if (this.left == null)
this.left = new BinaryTree<T>(value);
else
this.left.add(value);
}
else
{
if (this.right == null)
this.right = new BinaryTree<T>(value);
else
this.right.add(value);
}
}
}
Here is how the recursive function look like
private void mirrorSymmetricTree(MirrorTreeNode<T> m, BinaryTreeNode<T> n)
{
if (n == null) // base case
{
return;
}
if (n.left != null)
{
m.left = new MirrorTreeNode<T>(n.left.value);
mirrorSymmetricTree(m.left, n.left);
}
if (n.right != null)
{
m.right = new MirrorTreeNode<T>(n.right.value);
mirrorSymmetricTree(m.right, n.right);
}
}
public static MirrorTree mirrorSymmetricTree(BinaryTree<T> t)
{
if (t == null)
{
return null;
}
if (t.root != null)
{
this.root = new MirrorTreeNode<T>(t.root.value);
mirrorSymmetricTree(this.root, t.root);
}
return this;
}
Where your MirrorTree node would look like this
class MirrorTreeNode<T extends Comparable<T>>
{
public T value;
public MirrorTreeNode<T> left;
public MirrorTreeNode<T> right;
public MirrorTreeNode<T> (T value)
{
this.value = value;
this.left = null;
this.right = null;
}
..
}
Then you can mirror a tree by calling mirrorSymmetricTree on a BinaryTree
BinaryTree<String> t1 = new BinaryTree<>();
t1.addAll({"D","B","F","A","C","E","G"});
// D
// B F
// A C E G
t1.printDFS();
// A, B, C, D, E, F, G
MirrorTree<String> t2 = new MirrorTree<>();
t2.mirrorSymmetricTree(t1);
// t2 is a copy of t1 now
t2.printDFS();
// A, B, C, D, E, F, G
Notes
In order to mirror a binary tree of size N, you have to visit every node in that tree once, thus mirroring a tree has time complexity of O(N)
In order to mirror a binary tree, the items you store has to be Comparable, meaning they can be compared to find out if this.value > input or this.value < input to decide where to put it in the tree
In order to make sure the items are Comparable, you either implement this manually, or you demand that template type has to implement Comparable<T> interface, which force T to have compareTo function that let you compare values\keys as if they were numbers, where A.compareTo(B) > 0 is equivlant to A > B

Related

Problem with recursive method for BST rRemove(BSTNode<T> current, T data, BSTNode<T> dummy) when using pointer reinforcement technique

Here is the Node class:
public class BSTNode<T extends Comparable<? super T>> {
private T data;
private BSTNode<T> left;
private BSTNode<T> right;
BSTNode(T data) {
this.data = data;
}
T getData() {
return data;
}
BSTNode<T> getLeft() {
return left;
}
BSTNode<T> getRight() {
return right;
}
void setData(T data) {
this.data = data;
}
void setLeft(BSTNode<T> left) {
this.left = left;
}
void setRight(BSTNode<T> right) {
this.right = right;
}
}
Here is my BST class with main driver method:
import java.util.NoSuchElementException;
public class BST<T extends Comparable<? super T>> {
private BSTNode<T> root;
private int size;
BST() {
root = null;
}
public void add(T data) {
if (data == null) {
throw new IllegalArgumentException("Error: Data can't be null");
}
root = rAdd(root, data);
}
private BSTNode<T> rAdd(BSTNode<T> current, T data) {
if (current == null) {
size++;
return new BSTNode<T>(data);
} else if (data.compareTo(current.getData()) < 0) {
current.setLeft(rAdd(current.getLeft(), data));
} else if (data.compareTo(current.getData()) > 0) {
current.setRight(rAdd(current.getRight(), data));
}
return current;
}
public T remove(T data) {
if (data == null) {
throw new IllegalArgumentException("Error: data can't be null");
}
BSTNode<T> dummy = new BSTNode<>(null);
root = rRemove(root, data, dummy);
return dummy.getData();
}
private BSTNode<T> rRemove(BSTNode<T> current, T data, BSTNode<T> dummy) {
if (current == null) {
throw new NoSuchElementException("Error: Data not present");
} else if (data.compareTo(current.getData()) < 0) {
current.setLeft(rRemove(current.getLeft(), data, dummy));
} else if (data.compareTo(current.getData()) > 0) {
current.setRight(rRemove(current.getRight(), data, dummy));
} else {
System.out.println("Data found ... ");
dummy.setData(current.getData());
size--;
if (current.getRight() == null && current.getLeft() == null) {
if (current.equals(root)) {
this.root = null;
}
return null;
} else if (current.getLeft() != null) {
return current.getLeft();
} else if (current.getRight() != null) {
return current.getRight();
} else {
BSTNode<T> dummy2 = new BSTNode<>(null);
current.setRight(removeSuccessor(current.getRight(), dummy2));
current.setData(dummy2.getData());
}
}
return current;
}
private BSTNode<T> removeSuccessor(BSTNode<T> current, BSTNode<T> dummy) {
if (current.getLeft() == null) {
dummy.setData(current.getData());
return current.getRight();
} else {
current.setLeft(removeSuccessor(current.getLeft(), dummy));
}
}
public List<T> inorder(BSTNode<T> root) {
ArrayList<T> inorderContents = new ArrayList<T>();
if (root == null) {
return inorderContents;
}
inorderR(inorderContents, root);
return inorderContents;
}
private void inorderR(ArrayList<T> inorderContents, BSTNode<T> current) {
if (current == null) {
return;
}
inorderR(inorderContents, current.getLeft());
inorderContents.add(current.getData());
inorderR(inorderContents, current.getRight());
}
public BSTNode<T> getRoot() {
// DO NOT MODIFY THIS METHOD!
return root;
}
public int size() {
// DO NOT MODIFY THIS METHOD!
return size;
}
public static void main(String[] args) {
BST bst3 = new BST<>();
bst3.add(1);
bst3.add(0);
bst3.add(5);
bst3.add(4);
bst3.add(2);
bst3.add(3);
System.out.println(bst3.inorder(bst3.getRoot() ));
bst3.remove(1);
System.out.println(bst3.inorder(bst3.getRoot() ));
}
}
My IDE (IntelliJ) says I am missing a return statement for my removeSuccessor(BSTNode current, BSTNode dummy) method but I expected it to recurse to the base case reinforcing the unchanged nodes.
As a result when I try and remove from a two child node it returns zero although the one child and zero child cases work .
Please can someone tell me what is wrong with my two child node remove case? Thanks, Sperling.
First, you need to modify the if-else by changing the conditions:
if (current.getLeft() != null && current.getRight() == null) {
return current.getLeft();
} else if (current.getRight() != null && current.getLeft() == null) {
return current.getRight();
}
instead of the same without the 2nd arguments of && in the rRemove() method.
Then, use this:
private BSTNode<T> removeSuccessor(BSTNode<T> current, BSTNode<T> dummy) {
if (current.getLeft() == null) {
dummy.setData(current.getData());
return current.getRight();
} else {
current.setLeft(removeSuccessor(current.getLeft(), dummy));
return current;
}
}
Meaning of this method is as follows: delete the lowest value in the tree and return new root, as well as remember the value using dummy.
If we get nothing to the left, it's trivial - we delete current node, return getRight() and set a value to dummy.
On the other hand, if we get something to the left then we know that our current node will be the root, but before we return it we need to remove the lowest entry to the left, and so we use the function recursively, also setting current.left to be it's return value to properly transform the tree. We pass dummy so that it can get a value when the first case occurs, and then it's communicated to the highest call (inside the first function).
It's also possible to do it without recursion:
private BSTNode<T> removeSuccessor2(BSTNode<T> current, BSTNode<T> dummy) {
BSTNode<T> root = current;
BSTNode<T> prev = null;
while(current.getLeft() != null) {
prev = current;
current = current.getLeft();
}
/* current.getLeft == null */
//we will delete current
if (prev == null) { //no loop iterations -- current is the root
dummy.setData(current.getData());
return(current.getRight());
}
else {//some iterations passed, prev.getLeft() == curret
dummy.setData(current.getData());
prev.setLeft(current.getRight());
return root;
}
}
With dummy we return the value, the rest is transforming the tree.
Note: It doesn't work in my version for current == null. You should be able to modify it easily, though. Also, for clarity I didn't pull the dummy.setData... before if...else etc. Modify it as you wish!

Creating a binary search tree in java. But output is null

I am trying to create a rudimentary binary search tree in java with an insert and traverse method. The nodes have two local variables, a string and an int, the String value is used to sort the nodes.
Each BST has a local variable pointer to the root node and the nodes are inserted by traversing from the node. There seems to be a problem in creating the root node as my output is consistently producing null instead of.
THE
CAT
HAT
class BST
{
public Node root = null;
private class Node
{
private String key;
private int value;
private Node left;
private Node right;
public Node ()
{
}
public Node (String key, int value)
{
this.key = key;
this.value = value;
}
public String toString ()
{
return ("The key is: "+ this.key +" "+ this.value);
}
}
BST ()
{
}
public void put (String key, int value)
{
put (root, key, value);
}
private void put (Node x, String key, int value)
{
Node newNode = new Node(key, value);
if (x == null)
{
x = newNode;
System.out.println("new node added");
System.out.println(x);
}
int cmp = key.compareTo(x.key);
if (cmp < 0)
put(x.left, key, value);
else if (cmp > 0)
put(x.right, key, value);
else
x.value = value;
}
public void inorder (Node x)
{
if (x != null)
{
inorder (x.left);
System.out.println(x.key);
inorder (x.right);
}
}
public static void main (String [] args)
{
BST bst = new BST();
bst.put(bst.root,"THE", 1);
bst.put(bst.root,"CAT", 2);
bst.put("HAT", 1);
bst.inorder(bst.root);
}
}
Parameters are passed by value. Use the method's return value to alter something:
public void put (String key, int value)
{
root = put (root, key, value);
}
private Node put (Node x, String key, int value)
{
Node newNode = new Node(key, value);
if (x == null)
{
System.out.println("new node added");
System.out.println(x);
return newNode;
}
int cmp = key.compareTo(x.key);
if (cmp < 0)
x.left = put(x.left, key, value);
else if (cmp > 0)
x.right = put(x.right, key, value);
else
x.value = value;
return x;
}
Refer below link , good explanation of BST
http://www.java2novice.com/java-interview-programs/implement-binary-search-tree-bst/
A binary search tree is a node-based data structure, the whole idea of a binary search tree is to keep the data in sorted order so we can search the data in a little faster.There are three kinds of nodes are playing key role in this tree (Parent Node,Left Child Node & Right Child Node).The value of the left child node is always lesser than the value of the parent node, the same as the value of the right child node is always greater than the value of the parent node. Each parent node can have a link to one or two child nodes but not more than two child nodes.
Please find the source code from my tech blog - http://www.algonuts.info/create-a-binary-search-tree-in-java.html
package info.algonuts;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
class BinaryTreeNode {
int nodeValue;
BinaryTreeNode leftChildNode;
BinaryTreeNode rightChildNode;
public BinaryTreeNode(int nodeValue) {
this.nodeValue = nodeValue;
this.leftChildNode = null;
this.rightChildNode = null;
}
public void preorder() {
System.out.print(this.nodeValue+" ");
if(this.leftChildNode != null) {
this.leftChildNode.preorder();
}
if(this.rightChildNode != null) {
this.rightChildNode.preorder();
}
}
public void inorder() {
if(this.leftChildNode != null) {
this.leftChildNode.inorder();
}
System.out.print(this.nodeValue+" ");
if(this.rightChildNode != null) {
this.rightChildNode.inorder();
}
}
public void postorder() {
if(this.leftChildNode != null) {
this.leftChildNode.postorder();
}
if(this.rightChildNode != null) {
this.rightChildNode.postorder();
}
System.out.print(this.nodeValue+" ");
}
}
class BinaryTreeCompute {
private static BinaryTreeNode temp;
private static BinaryTreeNode newNode;
private static BinaryTreeNode headNode;
public static void setNodeValue(int nodeValue) {
newNode = new BinaryTreeNode(nodeValue);
temp = headNode;
if(temp != null)
{ mapping(); }
else
{ headNode = newNode; }
}
private static void mapping() {
if(newNode.nodeValue < temp.nodeValue) { //Check value of new Node is smaller than Parent Node
if(temp.leftChildNode == null)
{ temp.leftChildNode = newNode; } //Assign new Node to leftChildNode of Parent Node
else
{
temp = temp.leftChildNode; //Parent Node is already having leftChildNode,so temp object reference variable is now pointing leftChildNode as Parent Node
mapping();
}
}
else
{
if(temp.rightChildNode == null)
{ temp.rightChildNode = newNode; } //Assign new Node to rightChildNode of Parent Node
else
{
temp = temp.rightChildNode; //Parent Node is already having rightChildNode,so temp object reference variable is now pointing rightChildNode as Parent Node
mapping();
}
}
}
public static void preorder() {
if(headNode != null) {
System.out.println("Preorder Traversal:");
headNode.preorder();
System.out.println("\n");
}
}
public static void inorder() {
if(headNode != null) {
System.out.println("Inorder Traversal:");
headNode.inorder();
System.out.println("\n");
}
}
public static void postorder() {
if(headNode != null) {
System.out.println("Postorder Traversal:");
headNode.postorder();
System.out.println("\n");
}
}
}
public class BinaryTree {
//Entry Point
public static void main(String[] args) {
ArrayList <Integer> intList = new ArrayList <Integer>(Arrays.asList(50,2,5,78,90,20,4,6,98));
Iterator<Integer> ptr = intList.iterator();
while(ptr.hasNext())
{ BinaryTreeCompute.setNodeValue(ptr.next()); }
BinaryTreeCompute.preorder();
BinaryTreeCompute.inorder();
BinaryTreeCompute.postorder();
}
}
Adding to the answer by #Maurice,
Your code has several problems:
You expect JAVA to be pass by reference, when it is pass by value. You should use the code given by Maurice instead.
You are comparing "keys", when you should compare values.
I suggest that you use following modified code :
public class BST
{
public Node root = null;
private class Node
{
private String key;
private int value;
private Node left;
private Node right;
public Node ()
{
}
public Node (String key, int value)
{
this.key = key;
this.value = value;
}
public String toString ()
{
return ("The key is: "+ this.key +" "+ this.value);
}
}
BST ()
{
}
public void put (String key, int value)
{
root = putInTree (root, key, value);
}
private Node putInTree (Node x, String key, int value)
{
Node newNode = new Node(key, value);
if (x == null)
{
x = newNode;
System.out.println("new node added");
System.out.println(x);
return newNode;
}
//int cmp = key.compareTo(x.key);
if (value < x.value)
x.left = putInTree(x.left, key, value);
else /*if (value >= x.value)*/
x.right = putInTree(x.right, key, value);
/*else
x.value = value;*/
return x;
}
public void inorder (Node x)
{
if (x != null)
{
inorder (x.left);
System.out.println(x.key);
inorder (x.right);
}
}
public static void main (String[] args)
{
BST bst = new BST();
bst.put("THE", 1);
bst.put("CAT", 2);
bst.put("HAT", 1);
bst.inorder(bst.root);
}
}

Java Binary Tree Main Method

I've got a class Node
class Node{
int val;
Node parent;
Node left;
Node right;
public Node (int val){
this.val = val;
}
}
And I have a few methods:
public class Tree{
public Node root = null;
void insertNodeSorted(Node x, Node tree) {
if (x.val < tree.val) {
if (tree.left == null) {
tree.left = x;
}
else
insertNodeSorted(x, tree.left);
}
else {
if (tree.right == null) {
tree.right = x;
}
else
insertNodeSorted(x, tree.right);
}
} // end insertNodeSorted
void deleteNodeSorted(Node x) {
if (root == null)
return;
else
root = deleteNodeSorted(x, root);
}
Node deleteNodeSorted(Node x, Node tree) {
if (x.val < tree.val)
tree.left = deleteNodeSorted(x, tree.left);
else if (x.val > tree.val)
tree.right = deleteNodeSorted(x, tree.right);
else
tree = replaceNodeSorted(tree);
return tree;
} // end deleteNodeSorted
// Additional Method
Node replaceNodeSorted(Node tree) {
if (tree.right == null)
tree = tree.left;
else if (tree.left == null)
tree = tree.right;
else
tree.right = findReplacement(tree.right, tree);
return tree;
} // end replaceNodeSorted
Node findReplacement(Node tree, Node replace) {
if (tree.left != null)
tree.left = findReplacement(tree.left, replace);
else {
replace.val = tree.val;
tree = tree.right;
}
return tree;
} // end findReplacement
And I'd like to compile the Tree, but I don't know what I exactly I need to write in the main method.
public static void main(String[] args){
Tree t = new Tree();
t.insertNodeSorted();
What do I have to write in the brackets in order to print the Tree? (I know I still have to add System.out.println(val); in the methods..)
You defined a variable holding the root node, so it is not necessary to pass the parameter tree for the method insertNodeSorted. You can use always the root node.
Add a method taking only one parameter.
public void insertNodeSorted(Node x) {
if (root == null) {
root = x;
return;
}
insertNodeSorted(x, root);
}
Define the other method with two parameters as private
private void insertNodeSorted(Node x, Node tree) {
...
}
Now you can insert elements as follow:
Tree t = new Tree();
t.insertNodeSorted(new Node(1));
t.insertNodeSorted(new Node(134));
t.insertNodeSorted(new Node(13));
t.insertNodeSorted(new Node(4));
...

Java Generics: compareTo and “capture#-of ?”

I'm trying to write an implementation of a BinaryTree whose object can be of any type that implements Comparable. However, I realize that won't completely work. For example, A String and a Double wouldn't be able to be inserted into the same tree, even though they both implement Comparable.
So, I would like to know if it's possible to write the code such that the BinaryTree can be instantiated with any value whose type implements Comparable, but any ensuing elements added to the tree must all share the same supertype as the root's value.
Here's the code I have so far:
public class BinaryTree {
private Node root;
public BinaryTree() {
this.root = null;
}
public Node lookup(Comparable<Object> value) {
return lookup(this.root, value);
}
private Node lookup(Node node, Comparable<Object> value) {
Node match = null;
if (match != node) {
if (value == node.value) {
match = node;
} else if (value.compareTo(node.value) < 0) {
return lookup(node.left, value);
} else {
return lookup(node.right, value);
}
}
return match;
}
public Node lookupNonRecursively(Comparable<Object> value) {
return lookupNonRecursively(this.root, value);
}
private Node lookupNonRecursively(Node node, Comparable<Object> value) {
Node match = null;
if (match != node) {
if (value == node.value) {
match = node;
} else {
Node root = node;
boolean found = false;
while (!found && root != null) {
if (root.value.compareTo(value) < 0) {
if (root.left == null) {
root.left = match = new Node(value);
found = true;
} else {
root = root.left;
}
} else {
if (root.right == null) {
root.right = match = new Node(value);
found = true;
} else {
root = root.right;
}
}
}
}
}
return match;
}
public Node insert(Comparable<Object> value) {
return insert(this.root, value);
}
private Node insert(Node node, Comparable<Object> value) {
if (node == null) {
node = new Node(value);
} else {
if (node.value.compareTo(value) <= 0) {
insert(node.left, value);
} else {
insert(node.right, value);
}
}
return node;
}
public Node insertNonRecursively(Comparable<Object> value) {
return insertNonRecursively(this.root, value);
}
private Node insertNonRecursively(Node node, Comparable<Object> value) {
if (node == null) {
node = new Node(value);
} else {
Node root = node;
boolean inserted = false;
while (!inserted) {
if (node.value.compareTo(root.value) < 0) {
if (root.left == null) {
root.left = node = new Node(value);
inserted = true;
} else {
root = root.left;
}
} else {
if (root.right == null) {
root.right = node = new Node(value);
inserted = true;
} else {
root = root.right;
}
}
}
}
return node;
}
public static class Node {
private Node left;
private Node right;
private Comparable<Object> value;
public Node(Comparable<Object> value) {
this.left = null;
this.right = null;
this.value = value;
}
}
}
And as a test, this will throw the error, The method insert(Comparable<Object>) in the type BinaryTree is not applicable for the arguments (Integer), if I try to run code like the following:
BinaryTree tree = new BinaryTree();
tree.insert(new Integer(1));
You can see I've implemented some different BinaryTree methods for this class, but the same rules would need to apply: any value passed into lookup() or insert() would also need to share the root's supertype. I have a feeling this is where some variant of <T extends Comparable<? super T>> is going to come into play, but my mind is just not figuring this one out.
Any ideas for how I might accomplish this?
As noted by #jp-jee, here's my solution (also with logic and other bugs fixed from untested first attempt), which works beautifully:
public class BinaryTree<T extends Comparable<T>> {
private Node<T> root;
public BinaryTree() {
this.root = null;
}
public Node<T> lookup(T value) {
return lookup(this.root, value);
}
private Node<T> lookup(Node<T> node, T value) {
Node<T> match = null;
if (match != node) {
if (value.equals(node.value)) {
match = node;
} else if (value.compareTo(node.value) < 0) {
return lookup(node.left, value);
} else {
return lookup(node.right, value);
}
}
return match;
}
public Node<T> lookupNonRecursively(T value) {
return lookupNonRecursively(this.root, value);
}
private Node<T> lookupNonRecursively(Node<T> node, T value) {
Node<T> match = null;
if (match != node && value != null) {
if (value.equals(node.value)) {
match = node;
} else {
Node<T> searchRoot = node;
boolean found = false;
while (!found && searchRoot != null) {
if (value.equals(searchRoot.value)) {
match = searchRoot;
found = true;
} else if (value.compareTo(searchRoot.value) < 0) {
searchRoot = searchRoot.left;
} else {
searchRoot = searchRoot.right;
}
}
}
}
return match;
}
public void insert(T value) {
this.root = insert(this.root, value);
}
private Node<T> insert(Node<T> node, T value) {
if (node == null) {
node = new Node<T>(value);
} else {
if (value.compareTo(node.value) <= 0) {
node.left = insert(node.left, value);
} else {
node.right = insert(node.right, value);
}
}
return node;
}
public void insertNonRecursively(T value) {
this.root = insertNonRecursively(this.root, value);
}
private Node<T> insertNonRecursively(Node<T> node, T value) {
if (node == null) {
node = new Node<T>(value);
} else {
Node<T> runner = node;
boolean inserted = false;
while (!inserted) {
if (value.compareTo(runner.value) < 0) {
if (runner.left == null) {
runner.left = new Node<T>(value);
inserted = true;
} else {
runner = runner.left;
}
} else {
if (runner.right == null) {
runner.right = new Node<T>(value);
inserted = true;
} else {
runner = runner.right;
}
}
}
}
return node;
}
public static class Node<T extends Comparable<T>> {
private Node<T> left;
private Node<T> right;
private T value;
public Node(T value) {
this.left = null;
this.right = null;
this.value = value;
}
public Node<T> getLeft() {
return left;
}
public Node<T> getRight() {
return right;
}
public T getValue() {
return value;
}
}
}
Make your Binary Tree generic like
public class BinaryTree<T extends Comparable<T>>{
...
}
Whenever creating a BinaryTree instance, specify the containied type:
new BinaryTree<MyClass>();
Where MyClass must implement Comparable<MyClass>, i.e. be comparable to Objects of the same class.
Your methods would read as (example):
public Node lookup(T value) { ... }
The same applies for your Node class. Make it generic the same way.

Problem calling multiple instances of a class in java

i have a problem calling multiple instance of a class that i have coded (Tree, TreeNode)
in the main method, the system would give the output c d j c d j even though both trees are obviously different trees.
if i were to separate both postOrder() calls(each called after the tree has been pushed in to the stack)
Stack<Tree> alphaStack = new Stack<Tree>();
TreeNode a = new TreeNode('i');
Tree tree = new Tree(a);
TreeNode newleft = new TreeNode('a');
TreeNode newright = new TreeNode('b');
tree.setLeft(a, newleft);
tree.setRight(a, newright);
alphaStack.push(tree);
Tree.postOrder(alphaStack.pop().getRoot());
TreeNode b = new TreeNode('j');
Tree newtree = new Tree(b);
TreeNode left = new TreeNode('c');
TreeNode right = new TreeNode('d');
newtree.setLeft(b, left);
newtree.setRight(b, right);
alphaStack.push(newtree);
Tree.postOrder(alphaStack.pop().getRoot());
the output would be a b i c d j.
Does this mean that my class is not being duplicated but instead being reused when i make new Trees?
Below is the code:
import java.util.Stack;
public class mast_score {
public static void main(String[] args){
Stack<Tree> alphaStack = new Stack<Tree>();
TreeNode a = new TreeNode('i');
Tree tree = new Tree(a);
TreeNode newleft = new TreeNode('a');
TreeNode newright = new TreeNode('b');
tree.setLeft(a, newleft);
tree.setRight(a, newright);
alphaStack.push(tree);
TreeNode b = new TreeNode('j');
Tree newtree = new Tree(b);
TreeNode left = new TreeNode('c');
TreeNode right = new TreeNode('d');
newtree.setLeft(b, left);
newtree.setRight(b, right);
alphaStack.push(newtree);
Tree.postOrder(alphaStack.pop().getRoot());
Tree.postOrder(alphaStack.pop().getRoot());
} }
code for TreeNode
public class TreeNode{
Object item;
TreeNode parent;
TreeNode left;
TreeNode right;
public TreeNode (Object item) {
this.item = item;
parent = null;
left = null;
right = null;
}
public TreeNode getParent(TreeNode current) throws ItemNotFoundException
{
if(current == null) throw new ItemNotFoundException("No parent");
if(current.parent == null) throw new ItemNotFoundException("This
is the root");
else return current.parent;
}
public TreeNode getLeft(TreeNode current) throws ItemNotFoundException
{
if(current == null) throw new ItemNotFoundException("No left or
right child");
if(current.left == null) throw new ItemNotFoundException("No left
child");
else return current.left;
}
public TreeNode getRight(TreeNode current) throws ItemNotFoundException
{
if(current == null) throw new ItemNotFoundException("No left or
right child");
if(current.right == null) throw new ItemNotFoundException("No
right child");
else return current.right;
}
public Object getElement() throws ItemNotFoundException {
if(this.item == null) throw new ItemNotFoundException("No such
node");
else return this.item;
} }
code for Tree class
import java.util.*;
public class Tree {
static TreeNode root;
int size;
public Tree() {
root = null;
}
public Tree(TreeNode root) {
Tree.root = root;
}
public TreeNode getRoot() {
return this.root;
}
public int getLvl(TreeNode node) {
return node.lvlCount;
}
public void setLeft(TreeNode node, TreeNode left) {
node.left = left;
}
public void setRight(TreeNode node, TreeNode right) {
node.right = right;
}
public static void postOrder(TreeNode root) {
if (root != null) {
postOrder(root.left);
postOrder(root.right);
System.out.print(root.item + " ");
} else {
return;
}
}
public static int getSize(TreeNode root) {
if (root != null) {
return 1 + getSize(root.left) +
getSize(root.right);
} else {
return 0;
}
}
public static boolean isEmpty(Tree Tree) {
return Tree.root == null;
} }
Your problem is here, in the Tree class:
static TreeNode root;
You should remove the word static, and replace Tree.root with this.root.
Adding the keyword static causes the variable root to be shared between all instances of Tree in your program, which is not what you want.

Categories

Resources