I ran into problem and can't figure it out why my nodes are not being added to a Binary Tree. I feel like it sets the node and than in the next loop it resets it.
E is a Customer object
T is a LinkedList, list of integers.
I'm not sure if I have to implement the Interface parent also.
I can see in console that it always sets nodes to the right.
Where's the error in my code?
Update:
If I replace in the add method
BinaryNode<E, T> parent = new BinaryNode<>() ;
with
Parent<E, T> parent = this;
Then it seems like its going into while loop and compares, I can see println statements in a console. But then I get an error:
Exception in thread "main" java.lang.ClassCastException:
teama.tree.BinaryNode cannot be cast to teama.tree.Parent
at teama.tree.BinarySearchTree.add(BinarySearchTree.java:32)
at teama.tree.TestBtree.main(TestBtree.java:44)
and this code is highlighted and offering cast it to a BinaryNode:
parent = (Parent<E, T>) node;
If I remove the cast from it
parent = node;
then it highlight the node with the red underline and offers it to cast back.
Why does this happen and how to fix it?
Here's the code:
public class BinaryNode<E, T> {
/** The item associated with this node. */
private E item;
private T item2;
/** The node at the root of the left subtree. */
private BinaryNode<E, T> left;
/** The node at the root of the right subtree. */
private BinaryNode<E, T> right;
public BinaryNode() {
}
/** Put item in a leaf node. */
public BinaryNode(E item, T item2) {
this.item = item;
this.item2 = item2;
public void setChild(int direction, BinaryNode<E, T> child) {
if (direction < 0) {
System.out.println("set Left");
left = child;
} else {
System.out.println("set Right");
right = child;
}
}
Here's BinaryTree class
public class BinarySearchTree <E extends Comparable<E>, T>
implements Parent<E, T>, Set<E> {
{
/** Root node. */
private BinaryNode<E, T> root;
/** A BinarySearchTree is initially empty. */
public BinarySearchTree() {
root = null;
}
Here I had to replace Parent<E,T> with the BinaryNode<E, T>, because nodes below were offered to cast by Eclipse, mismatch type.
public void add(E target, T list) {
// Here I replaced Parent<E> parent = this;
// with BinaryNode<E, T> parent = new BinaryNode<>()
BinaryNode<E, T> parent = new BinaryNode<>() ;
BinaryNode<E, T> node = root;
int comparison = 0;
while (node != null) {
System.out.println("While loop:");
comparison = target.compareTo(node.getItem());
System.out.println("Comparison=" + comparison);
if (comparison < 0) { // Go left
System.out.println("Go Left");
parent = node;
node = node.getLeft();
} else if (comparison == 0) {
// It's already here
return;
} else {
// Go right
System.out.println("Go Right");
parent = node;
node = node.getRight();
}
}
System.out.println("from add method: " + target +" list=" + list);
// BinaryNode<E, T> newNode = new BinaryNode<E, T>(target, list);
// newNode.setChild(comparison, newNode);
parent.setChild(comparison, new BinaryNode<E, T>(target, list));
}
And Parent interface:
public interface Parent<E, T> {
/**
* Return the left child if direction < 0, or the right child
* otherwise.
*/
public BinaryNode<E, T> getChild(int direction);
/**
* Replace the specified child of this parent with the new child.
* If direction < 0, replace the left child. Otherwise, replace
* the right child.
*/
public void setChild(int direction, BinaryNode<E, T> child);
I think I got it resolved. In my BinaryNode class I haven't implemented interface parent, and that's why it was giving me mismatch error type. After I added implements Parent<E> to public class BinaryNode<E, T> it works fine now.
Related
I did a code about inserting nodes in a binary tree ... My code is not working because of some reasons in my add method , please look at my comments next to each line .. here is my code where I get problem with ..
public class BinarySearchTree<E extends Comparable<? super E>> {
BinaryNode<E> root;
/**
* Constructs an empty binary searchtree.
*/
public BinarySearchTree() {
}
/**
* Inserts the specified element in the tree if no duplicate exists.
* #param x element to be inserted
* #return true if the the element was inserted
*/
public boolean add(E element) {
BinaryNode newNode = new BinaryNode(element);
if(root==null){
root=newNode;
} if (element==this.element){ // element cannot be resolved or is not a field
return false;
} else {
BinaryNode<E> focus = root;
BinaryNode parent;
while(true) {
parent=focus;
if (element < focus.element) { //The operator < is undefined for the argument type(s) E, Object
focus=focus.left;
if (focus==null) {
parent.left=newNode;
return true;
}
} else {
focus=focus.right;
if (focus==null) {
parent.right=newNode; //
}
return true;
}
}
}
}
static class BinaryNode<E> {
E element;
BinaryNode<E> left;
BinaryNode<E> right;
private BinaryNode(E element) {
this.element = element;
}
}
}
How to correct my errors?
Is my code suitable? Does it need to be changed?
Thank you
I changed your code where you make a compare element less than focus.element, i have puted element.compareTo(focus.element) < 0, is the way to compare thing without being an integer
public class BinarySearchTree<E extends Comparable<? super E>> {
BinaryNode<E> root;
/**
* Constructs an empty binary searchtree.
*/
public BinarySearchTree() {
}
/**
* Inserts the specified element in the tree if no duplicate exists.
* #param element to be inserted
* #return true if the the element was inserted
*/
public boolean add(E element) {
BinaryNode newNode = new BinaryNode(element);
if(root==null){
root=newNode;
System.out.println("root");
} if (element==root.element){ // element cannot be resolved or is not a field
return false;
} else {
BinaryNode<E> focus = root;
BinaryNode parent;
while(true) {
parent=focus;
if (element.compareTo(focus.element) < 0) { //Here is my change!!! The operator < is undefined for the argument type(s) E, Object
focus=focus.left;
System.out.println("left");
if (focus==null) {
parent.left=newNode;
return true;
}
} else {
focus=focus.right;
System.out.println("right");
if (focus==null) {
parent.right=newNode; //
}
return true;
}
}
}
}
static class BinaryNode<E> {
E element;
BinaryNode<E> left;
BinaryNode<E> right;
private BinaryNode(E element) {
this.element = element;
}
}
}
For my personal practice I am trying to make a basic, generic doubly linked list and I want to know if the methods addtoHead() and addtoTail() I made are correct and efficient and if not what would be better? and how could I remove from the list for the methods removingDataAt(), removingFromTail(), removingFromHead()?
Node class:
public class PracticeNode<T> {
private T data;
private PracticeNode<T> next;
private PracticeNode<T> prev;
PracticeNode() {
next = null;
prev = null;
data = null;
}
PratciceNode(T data) {
this(data, null, null);
}
PracticeNode(T data, PracticeNode<T> next, PracticeNode<T> prev) {
this.data = data;
this.next = next;
this.prev = prev;
}
public void setNextNode(PracticeNode<T> next) {
this.next = next;
}
public void setPrevNode(PracticeNode<T> prev) {
this.prev = prev;
}
public void setData(T data) {
this.data = data;
}
public PracticeNode<T> getNextNode() {
return next;
}
public PracticeNode<T> getPrevNode() {
return prev;
}
public T getData() {
return data;
}
}
Linked list class:
public class PracticeLinkedList<T> {
private PracticeNode<T> head;
private PracticeNode<T> tail;
public void addtoHead(T data ) {
PracticeNode<T> newnode=new PracticeNode<T>();
if(head==null){
head=newnode;
tail=newnode;
newnode.setNextNode(null);
newnode.setPrevNode(null);
}else{
newnode.setNextNode(head);
head.setPrevNode(newnode);
head=newnode;
}
}
public void addToTail(T data) {
PracticeNode<T> newnode=new PracticeNode<T>();
if(tail==null){
head=newnode;
tail=newnode;
newnode.setNextNode(null);
newnode.setPrevNode(null);
}else{
newnode.setPrevNode(tail);
tail.setNextNode(newnode);
tail=newnode;
}
}
public T removingDataAt (int){
//....
}
public T removingFromTail (){
//....
}
public T removingFromHead (){
//....
}
}
addToTail looks good to me.
With removingDataAt(), removingFromTail(), and removingFromHead(), you want to do what you have done with addToTail and addToHead. Because this seems like it is something from an assignment, I will not give the completed code, but just tell you how to do it.
I see that you have only the navigating instances of head and tail, I would recommend that you also implement a 'current' which will allow you to navigate through the List to do things such as removingDataAt(location). I'm not sure about the most efficient method of removing things, but with Java, it does garbage collection automatically so you could simply remove from the head by using head = head.getNextNode(). Removing from tail is a similar story.
For removingDataAt() you will need a method to find the data data first, unless the use already knows what is in each location of the list. Perhaps something like find(object) which will return an error message on fail and move the 'current' instance to the found object otherwise. You'd implement it by using something like this:
for(current = head; current!=null; current = current.getNextNode())
Remember to check if there are any other items in the linked list.
Here is a solid implementation of doubly linked list:
http://algs4.cs.princeton.edu/13stacks/DoublyLinkedList.java.html
Add method looks like this:
// add element to list
public void add(Item item) {
Node x = current.prev;
Node y = new Node();
Node z = current;
y.item = item;
x.next = y;
y.next = z;
z.prev = y;
y.prev = x;
N++;
index++;
lastAccessed = null;
}
What to note here:
a> <b> <c> <e> <f> <g
if you want to add d, then find e and add d
public void add(Item item) {
Node x = current.prev; //new before element : c
Node y = new Node(); //new node to store element
Node z = current; //new after element : e
y.item = item; //store value to the node : d.value=value
x.next = y; //link before element next : c>
y.next = z; //link element next : d>
z.prev = y; //link after element previous : <e
y.prev = x; //link after element previous : <d
N++; //increase number of elements on list counter
index++; //increase current position number
lastAccessed = null;
}
now you should have :
a> <b> <c> <d> <e> <f> <g
I have a TreeNode class that represents node of the binary tree.
public class TreeNode {
private static Object key=null;
private static Object value=null;
private TreeNode parent;
private TreeNode left=null;
private TreeNode right=null;
/**
* #return the value
*/
public static Object getValue() {
return value;
}
/**
* #param aValue the value to set
*/
public static void setValue(Object aValue) {
value = aValue;
}
public TreeNode()
{
this(key,value);
}
public TreeNode(Object key,Object value)
{
this.key = key;
this.value = value;
}
/**
* #return the key
*/
public Object getKey() {
return key;
}
/**
* #param key the key to set
*/
public void setKey(Object key) {
this.key = key;
}
/**
* #return the parent
*/
public TreeNode getParent() {
return parent;
}
/**
* #param parent the parent to set
*/
public void setParent(TreeNode parent) {
this.parent = parent;
}
/**
* #return the left
*/
public TreeNode getLeftChild() {
return left;
}
/**
* #param left the left to set
*/
public void setLeftChild(TreeNode left) {
this.left = left;
}
/**
* #return the right
*/
public TreeNode getRightChild() {
return right;
}
/**
* #param right the right to set
*/
public void setRightChild(TreeNode right) {
this.right = right;
}
}
I have a BinarySearchTree class
public class BinarySearchTree implements DataStructures.interfaces.BinarySearchTree {
private int size=0;
private TreeNode root = new TreeNode();
#Override
public void insert(Object key, Object value)
{
insertOperation(key,value,root);
}
private void insertOperation(Object element, Object value, TreeNode node)
{
if(node.getKey() == null) {
node.setKey(element);
node.setValue(value);
}
else
{
if((int) node.getKey() > (int) element)
{
if(node.getLeftChild() != null)
insertOperation(element,value,node.getLeftChild());
else
{
TreeNode child = new TreeNode(element, value);
child.setKey(element);
child.setValue(value);
child.setParent(node);
node.setLeftChild(child);
size++;
}
}
else if((int) node.getKey() <= (int) element)
{
if(node.getRightChild() != null)
insertOperation(element,value,node.getRightChild());
else
{
TreeNode child = new TreeNode(element, value);
child.setKey(element);
child.setValue(value);
child.setParent(node);
node.setRightChild(child);
size++;
}
}
}
}
///more methods
}
The problem is that when I create a child node and set the parent child link. The value of parent node (the node object that I passed) also gets updated and refers to child object.
That is not my intention.
I want to create a chain of treenode objects that can be accessed through the "root" treenode object.
But this is not happening and I do not understand what I am doing wrong.
I know that the problem lies in the logic of this code snippet (not just for inserting on left side but both for inserting left child and right), but I do not understand what exactly.
if(node.getLeftChild() != null)
insertOperation(element,value,node.getLeftChild());
else
{
TreeNode child = new TreeNode(element, value);
child.setKey(element);
child.setValue(value);
child.setParent(node);
node.setLeftChild(child);
size++;
}
All I am telling java to do is if the node in question does not have a left child then create a left child node and set the current node's left side object to the child object.
if the node in question does have a left child then inspect that child and see if the new node should be inserted in left or right by calling the same function for the child of the node in question ... I don't understand why node's (the TreeNode object passed) key gets updated, when i set child's key value.
Why are your key and value static Objects? This means all TreeNodes would share the same key/value. Remove the static keyword and it should work fine.
I don't quite get what you mean by
The problem is that when I create a child node and set the parent child link. The value of parent node (the node object that I passed) also gets updated and refers to child object.
but I did notice one thing that will result an error:
else if((int) node.getKey() <= (int) element)
When node.getKey() == element, it means the bst already has a node with "element" as the key, which should be another special case. Instead you're still traversing through its right child.
Also, it would be nice if you can elaborate your error more clearly...
Everyone. Anyone can help me how to start this question. I am not very clear about it. Very appreciate.
The question is:
Implement the add and member methods of the SetImpl.java. Note that it is strongly recommended that you do not allow duplicates during add - that would make other methods more challenging to implement.
The following is the java coding about SetImpl.java:
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class SetImpl<T> implements Set<T>{
// container class for linked list nodes
private class Node<T>{
public T val;
public Node<T> next;
}
private Node<T> root; // empty set to begin with
// no need for constructor
// add new element to the set by checking for membership.. if not
// then add to the front of the list
public void add(T val){
}
// delete element from the list - may be multiple copies.
public void delete(T val){
}
// membership test of list
public boolean member(T val){
return false;
}
// converts to a list
public List<T> toList(){
ArrayList<T> res;
return res;
}
// does simple set union
public void union(Set<T> s){
}
}
Anyone can give me some tips about this question?
Thanks very much!
First try
private Node < T > root = null;
private Node < T > head = null;
private Node < T > tail = null;
public void add(T val) {
if (head == null) {
head = tail = new Node < T > ();
head.val = val;
root.next = tail;
tail = head;
} else {
tail.next = new Node < T > ();
tail = tail.next;
tail.val = val;
}
}
Okay here is just hints on how you should go in your logic :
public class SetImpl<T> implements Set<T>{
// container class for linked list nodes
///// It is said "Linked list" --> first hint google that
private class Node<T>{
public T val;
public Node<T> next;
}
private Node<T> root; // empty set to begin with
///// So that's my "root" which means I will have descendants
// no need for constructor
// add new element to the set by checking for membership.. if not
// then add to the front of the list
// Basically here everything is said.
// 1- check membership
// 2- if true do nothing (as it has been said, it's a Set, if you don't know why I say that google Set Collections
//if false (which means the val I want to add is not in my set) then I can add it to the Set
public void add(T val){
}
// delete element from the list - may be multiple copies.
public void delete(T val){
}
// membership test of list
// that's recursive calls. How do you check that? where do you store your values?
// It's true if your current Node.val attribute == the value OR if the rest of the Nodes has the value as member. Here you really need to know about Linked List
public boolean member(T val){
return false;
}
// converts to a list
public List<T> toList(){
ArrayList<T> res;
return res;
}
// does simple set union
public void union(Set<T> s){
}
}
Your implementation
private Node < T > root = null;
private Node < T > head = null;
private Node < T > tail = null;
public void add(T val) {
if (head == null) {
head = tail = new Node < T > ();
head.val = val;
root.next = tail;
tail = head;
} else {
tail.next = new Node < T > ();
tail = tail.next;
tail.val = val;
}
}
My guess is you don't need to add fields in such exercises. It's already half baked for you. Check out how linked list works. I'm lazy so I provide first "linked list" result from google. :)
Have fun
In the code below, the nodes of a postorder tree traversal is always printed
I m wondering if there is a way to store these nodes in the postorder sequence in an array
Do i have to do the traversal in a iterative way?
public static void postOrder(TreeNode root) {
if (root != null) {
postOrder(root.left);
postOrder(root.right);
System.out.print(root.item + " ");
} else {
return;
}
}
Just pass a List along with that method. Untested pseudo-ish code:
class Tree {
private TreeNode root;
// ...
public List<TreeNode> postOrder() {
List<TreeNode> nodes = new ArrayList<TreeNode>();
fillList(root, nodes);
return nodes;
}
private void fillList(TreeNode node, List<TreeNode> nodeList) { // private!
if(node != null) {
fillList(node.left, nodeList);
fillList(node.right, nodeList);
nodeList.add(node);
}
}
}
I would recommend a list instead of an array. That way you don't need to worry about the size of your tree. (Using an array you should first count the nodes in your tree, which would practically require another full traversal.) Storing the tree nodes themselves is achieved by this method:
public static void postOrder(TreeNode root, List<TreeNode> list) {
if (root != null) {
postOrder(root.left, list);
postOrder(root.right, list);
list.add(root);
} else {
return;
}
}
If you want to store only the items (supposing their type is TreeNodeItem):
public static void postOrder(TreeNode root, List<TreeNodeItem> list) {
if (root != null) {
postOrder(root.left, list);
postOrder(root.right, list);
list.add(root.item);
} else {
return;
}
}
The need to create the final array is ugly, but here's a mock-up, including a potential definition of type TreeNode:
final class TreeAccumulator
{
public static final class TreeNode<T>
{
public TreeNode(T item,
TreeNode<? extends T> left,
TreeNode<? extends T> right) {
this.item = item;
this.left = left;
this.right = right;
}
public final T item;
public final TreeNode<? extends T> left;
public final TreeNode<? extends T> right;
}
public static <T, C extends Collection<T>>
C postOrder(TreeNode<? extends T> root, C acc)
{
if (null == root)
return acc;
final C result = postOrder(root.right,
postOrder(root.left, acc));
result.add(root.item);
return result;
}
#SuppressWarnings({"unchecked"})
public static <T> T[] postOrder(TreeNode<? extends T> root,
Class<T> c)
{
final Collection<T> acc = postOrder(root, new LinkedList<T>());
return acc.toArray((T[])Array.newInstance(c, acc.size()));
}
}
If you knew more about the potential size of the tree ahead of time, you could collect into a pre-allocated ArrayList -- or even a primitive array -- more easily.