I created a binary tree using templates. I entered integer values for all the nodes and I want to find the maximum element in the Binary Tree.
Here is the implementation:
public class BinaryTreeNode<T> {
private T data;
BinaryTreeNode right;
BinaryTreeNode left;
public BinaryTreeNode(T data) {
this.data = data;
this.right = null;
this.left = null;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public BinaryTreeNode getRight() {
return right;
}
public void setRight(BinaryTreeNode right) {
this.right = right;
}
public BinaryTreeNode getLeft() {
return left;
}
public void setLeft(BinaryTreeNode left) {
this.left = left;
}
public int findMax(BinaryTreeNode root){
int max= 0;
if(root==null){
return 0;
} else {
int left= findMax(root.left);
int right= findMax(root.right);
max= Math.max(left,right);
if(max> root.getData()){
max= root.getData();
}
return max;
}
}
}
I am getting the following errors:
incompatible types: required int found java.lang.Object.
I wrote this in the modified version:
int data= Integer.valueOf((String)root.getData());
Is there a better way to do it?
root.getData() has a generic type T. This means you can't assume it will be an Integer, you can't determine which of two nodes has a higher value using Math.max() and findMax() should return T, not an int.
In order to find the max element, you must either require that T extends Comparable<T>, which will allow you to compare the data of two BinaryTreeNodes using compareTo(), or you should pass a Comparator<T> instance to the constructor of your tree, which will allow you to compare the data of BinaryTreeNodes using compare().
You must also avoid using the raw type BinaryTreeNode. Replace it will BinaryTreeNode<T> in all your methods. Otherwise, method call such as root.getData() will return an Object instead of T.
Using Comparable:
public class BinaryTreeNode<T extends Comparable<T>>
{
...
public T findMax(BinaryTreeNode<T> root) {
T max = null;
if(root == null) {
return null;
} else {
T left = findMax(root.left);
T right = findMax(root.right);
max = left.compareTo(right) <= 0 ? right : left;
if(max.compareTo(root.getData()) < 0) {
max = root.getData();
}
return max;
}
}
...
}
Related
hey I am new in the binary trees world and I am trying to compare to values to know which direction should I place the newly added node next.
for now, I tried to do CompareTo method but didn't succeed very much I am now trying to make a private method that will give me the value of the Nodes i would love some help
this is my code now I need to add to the if statement the comparing of nodes so I can proceed :
public void add(E data) {
if(root == null) {
return ;
}
if(root.getLeftSon() == null) {
root.setLeftSon((Node<E>) data);
}
else if(root.getRightSon() == null) {
root.setRightSon((Node<E>) data);
}
}
you have to use generics correctly. Parameter has to extend comparable so you can determinate how to sort it.
class BinaryTree<T extends Comparable<T>> {
Node<T> root;
public Node<T> addRecursive(Node<T> current, T value) {
if (current == null) {
return new Node<T>(value);
}
int ord = value.compareTo(current.value);
if (ord > 0) {
current.left = addRecursive(current.left, value);
} else if (ord < 0) {
current.right = addRecursive(current.right, value);
} else {
// value already exists
return current;
}
return current;
}
static class Node<T extends Comparable<T>> {
T value;
Node<T> left;
Node<T> right;
Node(T value) {
this.value = value;
right = null;
left = null;
}
}
}
I am getting this mystical error:
The operator > is undefined for the argument type(s)
java.lang.Comparable, java.lang.Comparable
What the heck?
(here's the code)
public class BST<T extends Comparable<T>> {
public static class Node<P extends Comparable<P>> {
P val;
Node<P> left;
Node<P> right;
public Node() {
}
public Node(P val) {
this.val = val;
}
}
Node<T> root;
private void addValHelper(Node root, Node newNode) {
if (root.val > newNode.val) { // <-- ERROR IS HERE
if (root.left == null) {
root.left = newNode;
} else {
addValHelper(root.left, newNode);
}
} else {
if (root.right == null) {
root.right = newNode;
} else {
addValHelper(root.right, newNode);
}
}
}
}
Java doesn't have operator overloading. You can't compare Comparable types with >. You need to use root.val.compareTo(newNode.val) instead.
As an aside:
Comparable is an interface, not a class
You don't need to specify <P extends Comparable<P>>
It might make more sense to move the addValHelper code into the Node class itself
It might make sense for Node to implement Comparable.
This way, your code feels a lot more idiomatic and you don't expose fields of Node to BST.
public class BST<T implements Comparable<T>> {
private final Node<T> root;
/** Presumably this is run when a value is added.. */
private void addValueHelper(Node rootNode, Node newNode) {
rootNode.attachChild(newNode);
}
public static class Node implements Comparable<T> {
private final T val;
private Node left;
private Node right;
public Node(T val) {
this.val = val;
}
public int compareTo(Node other) {
return this.val.compareTo(other.val);
}
/**
* Takes the given node and compares it with the current node.
* If the current node is greater than the given node, the given node is placed to the left.
* Otherwise it is placed to the right.
*/
protected void attachChild(Node newNode) {
if (this.compareTo(newNode) == 1) {
if (this.left == null) {
this.left = newNode;
return;
}
this.left.attachChild(newNode);
return;
}
if (this.right == null) {
this.right = newNode;
return;
}
this.right.attachChild(newNode);
}
}
}
I am implementing WAVL tree and WAVL node classes. In the WAVL node class I should create a method that counts how much internal nodes exist in the subtree of the node. I should do that in time complexity of O(1). Any suggestions?
The class I wrote is:
package coding_ex1;
public class WAVLNode
{
WAVLNode left;
WAVLNode right;
WAVLNode parent;
int rank;
int key;
String value;
public WAVLNode() //*constructor
{
this.left=null;
this.right=null;
this.parent=null;
this.rank=0;
this.key=0;
this.value=null;
}
public int getKey() //*gets WAVLNode. if external leaf, return -1. else, return key
{
if (this.rank==-1)
{
return -1;
}
return key;
}
public String getValue()//*gets WAVLNode. if external leaf, returns null. else, returns value
{
if (this.rank==-1)
{
return null;
}
return value;
}
public WAVLNode getLeft()//* get WAVLNode. returns left (if there is no left, the value of left is null)
{
return left;
}
public WAVLNode getReft()//* get WAVLNode. returns right (if there is no right, the value of right is null)
{
return right;
}
public boolean isInnerNode()//*gets WAVLNode. returns true for internal leaf. else, returns false
{
if(this.right!=null || this.left!=null)
{
return true;
}
return false;
}
}
You should add a filed and methods.
private int internalNodeCount = 0; // initially count as leaf
public int internalNodeCount() {
return internalNodeCount;
}
public void setLeft(WAVLNode node) {
this.left = node;
setInternalNodeCount();
}
public void setRight(WAVLNode node) {
this.right = node;
setInternalNodeCount();
}
void setInternalNodeCount() {
if (isInnerNode()) {
internalNodeCount = 1; // count for self
if (left != null)
internalNodeCount += left.internalNodeCount;
if (right != null)
internalNodeCount += right.internalNodeCount;
} else
internalNodeCount = 0;
}
Im trying to test a java generic class that i wrote, this is my test
public class BSTTest
{
public void testInsert()
{
int height;
BST<int> myTree = new BST<int>();
myTree.insert(1);
}
}
but when i compile i get the error of unexpected type, it says if found an int but requires a reference on the line of BST myTree = new BST(); what does that mean?
below are my Binary search tree and node class for reference
public class BST<E extends Comparable<E>>
{
public Node<E> root;
public BST()
{
root = null;
}
//insert delete find height
public void find(E s, Node<E> n)
{
//empty tree, root is null
if(n == null)
{
System.out.println("Item not present.");
}
//n is the node where s is, return n
else if(n.getData().equals(s))
{
System.out.println("Item present");
}
//s is greater than n, look for s on the right subtree
else if(s.compareTo(n.getData()) > 0)
{
find(s, n.getRight());
}
//s is less than n, look for s on the left subtree
else
{
find(s, n.getLeft());
}
}
public int height()
{
int count;
return count = height(root);
}
private int height(Node<E> n)
{
int ct = 0;
if(n == null)
{
}
else
{
int left = height(n.getLeft());
int right = height(n.getRight());
ct = Math.max(left, right) + 1;
}
return ct;
}
public void insert(E s)
{
root = insert(s, root);
}
private Node<E> insert(E s, Node<E> T)
{
//easiest case, empty tree, create new tree
if(T == null)
{
T = new Node<E>(s,null,null);
}
//easiest case, found s
else if(s.compareTo(T.getData()) == 0)
{
System.out.println("Item already present.");
}
//s is greater than T, insert on right subtree
else if(s.compareTo(T.getData()) > 0)
{
T.setRight(insert(s, T.getRight()));
}
//s is less than T, insert on left subtree
else
{
T.setLeft(insert(s,T.getLeft()));
}
return T;
}
public void delete(E d)
{
}
}
and my node class
public class Node<E>
{
private E data;
private Node<E> left;
private Node<E> right;
private Node<E> parent;
public Node(E d, Node<E> r, Node<E> l)
{
data = d;
left = l;
right = r;
}
public void setData(E d)
{
data = d;
}
public E getData()
{
return data;
}
public Node<E> getRight()
{
return right;
}
public void setRight(Node<E> nd)
{
right = nd;
}
public Node<E> getLeft()
{
return left;
}
public void setLeft(Node<E> nd)
{
left = nd;
}
public Node<E> getParent()
{
return parent;
}
public void setParent(Node<E> nd)
{
parent = nd;
}
}
Can you try Integer instead of int?
Generic type takes only Classes (Object types) and not the primite data type
It should be
BST<Integer> myTree = new BST<Integer>();
Java generics are only for Object types. Since, int is a primitive type you cannot use it. Instead use BST<Integer>
You can't use a primitive type like int as a parameter to a generic class in Java. It has to be a class type, such as Integer.
Im new to generics and i have to implement a binary search tree using generics. I did that but now im wondering how do i test the code that i wrote? Do i just make another class and start using the methods of the bst?
any help would be appreciated. below is my code just to clarify.
public class BST<E extends Comparable<E>>
{
public Node<E> root;
public BST()
{
root = null;
}
//insert delete find height
public void find(E s, Node<E> n)
{
//empty tree, root is null
if(n == null)
{
System.out.println("Item not present.");
}
//n is the node where s is, return n
else if(n.getData().equals(s))
{
System.out.println("Item present");
}
//s is greater than n, look for s on the right subtree
else if(s.compareTo(n.getData()) > 0)
{
find(s, n.getRight());
}
//s is less than n, look for s on the left subtree
else
{
find(s, n.getLeft());
}
}
public int height()
{
int count;
return count = height(root);
}
private int height(Node<E> n)
{
int ct = 0;
if(n == null)
{
}
else
{
int left = height(n.getLeft());
int right = height(n.getRight());
ct = Math.max(left, right) + 1;
}
return ct;
}
public void insert(E s)
{
root = insert(s, root);
}
private Node<E> insert(E s, Node<E> T)
{
//easiest case, empty tree, create new tree
if(T == null)
{
T = new Node<E>(s,null,null);
}
//easiest case, found s
else if(s.compareTo(T.getData()) == 0)
{
System.out.println("Item already present.");
}
//s is greater than T, insert on right subtree
else if(s.compareTo(T.getData()) > 0)
{
T.setRight(insert(s, T.getRight()));
}
//s is less than T, insert on left subtree
else
{
T.setLeft(insert(s,T.getLeft()));
}
return T;
}
public void delete(E d)
{
}
}
and my node class
public class Node<E>
{
private E data;
private Node<E> left;
private Node<E> right;
private Node<E> parent;
public Node(E d, Node<E> r, Node<E> l)
{
data = d;
left = l;
right = r;
}
public void setData(E d)
{
data = d;
}
public E getData()
{
return data;
}
public Node<E> getRight()
{
return right;
}
public void setRight(Node<E> nd)
{
right = nd;
}
public Node<E> getLeft()
{
return left;
}
public void setLeft(Node<E> nd)
{
left = nd;
}
public Node<E> getParent()
{
return parent;
}
public void setParent(Node<E> nd)
{
parent = nd;
}
}
Im trying to follow what you said, this is my test class
public class BSTTest
{
public void testInsert()
{
int height;
BST myTree = new BST();
myTree.insert(1);
}
}
but when i compile i get the error of unexpected type, it says if found an int but requires a reference on the line of BST myTree = new BST(); what does that mean?
Yes, make a class called BSTTest and create methods to test each of the public methods in BST.
If you use JUnit, you can use annotations and a standard naming convention
public class BSTTest {
#Test
public void testInsert() {
BST<String> bst = new BST<String>();
String s = "hello";
bst.insert(s);
AssertTrue("I should get back what I put in!", bst.find(s));
}
#Test
public void testDelete() {
// etc...
}
}
Then, you can run this 'Unit Test' in your java IDE (such as IntelliJ IDEA) or, if you have it set up, via maven: mvn test.
Also, I think your find() method could return boolean?
good luck!