Initiating a binary search tree using a rootNode that is null - java

I have this node class
public class Node {
Node right;
Node left;
int value;
Node(int value) {
this.value = value;
}
Node insertValue(int v){
if(this == null){
return new Node(v);
}
//Rest of the method
}
}
I want to make a rootNode that is the tree. If it is null, the tree is empty. Edit: The methods to populate the tree, find minimum, etc. must be recursive methods of class Node
class Main{
public static void main(String[] args) {
Node rootNode = null;
rootNode.insertValue(5);
}
}
Of course, since rootNode == null, I can't use it to call insertValue.
I am looking for a way to populate an empty tree(rootNode == null) with inner methods. Any tips on how I can do this?

You can create a new class Tree which contains (only) the root node and methods to work with like insertValue(). The Node class will become more or less a private helper class for the internals of the tree.
public class Tree {
private Node root;
public void insertValue(int v) {}
public int getSize() {}
public int getValue(int index) {}
}

Related

Best practice to build a BST from a Binary Tree

Im creating a Binary Search Tree in Java extending from a Binary Tree already implemented, but it does not work when I try to use some inherited methods. Let me explain:
Binary Tree:
public class BinaryTree<T>{
private Node<T> root;
public class Node<T>{
T value;
Node left;
Node right;
public Node(T value){
this.value = value;
this.left = null;
this.right = null;
}
}
public BinaryTree(){
...
}
public void printInOrder(){
...
}
}
BST:
public class BST extends BinaryTree<Integer>{
private Node<Integer> root;
public BST(Integer v){
super(v);
}
public void insert(Integer element){
insert(this.root, element);
}
private insert( Node node, Integer element){
if(node == null)
return;
if(node.value > value) {
if(node.left != null) {
insert(node.left, value);
}
else {
node.left = new NodeBST(value);
}
}else { // Node.value < element
if(node.right != null) {
insert(node.right, value);
}
else {
node.right = new NodeBST(value);
}
}
}
}
App:
public class App{
public static void main(String[] args){
BST bst = new BST(4);
bst.insert(2);
bst.insert(5);
bst.insert(3);
bst.insert(7);
bst.printInOrder(); //Here I got the problem
}
}
If I try to print it, it will just print the root (4) and will be null for the rest of the nodes. When I look what's going on inside, it turns out there is two roots:
BST.Node root, which contains all the nodes in the proper order
BinaryTree.Node root, which just contains the root and all the other nodes are null.
So I guess it creates the root correctly because I'm calling the super class in the BST' constructor, but when I creates a new Node in the insert method, it only appends it in BST.Node root (and not in the BinaryTree.Node root), therefore when I call print, which is implemented in BinaryTree, from BST in prints null :/
So my questios are:
How can I get to use the print method from BST in order to print all the values in BST.Node root?
What does prevent BinaryTree.Node root to be the same as BST.Node root?
What would be the best practice to do so?
Don't declare 'root' a second time in BST, it shadows the 'root' in the base class.
Either make 'root' in BinaryTree protected or provide the necessary accessors there, so subclasses can use it.

Why using a class as a variable member inside that said class

I am new to Java and been studying it. So I am having trouble to understand what are these and how it being processed by Java also why are we declaring these variables like that. I mean can you educate me on this?
Public abstract class ListItem {
protected Listitem leftLink = null;
protected Listitem rightLink = null;
protected Object value;
some code here
}
Thanks in advance!
Why declare a Class field which has the ClassName as variable type instead of a int, string... ?
Because the developer needs to. Sometimes, an instance of a class must reference another instance of the same class. A typical example is the LinkedList.
Consider a linked list as a sequence of nodes. Each node knows the next one to be linked. Here would be a naive implementation of a node:
class Node<T> {
private Node<T> next;
private T value;
Node(T value) {
this.value = value;
}
public T getValue() {
return value;
}
void setNext(Node<T> next) {
this.next = next;
}
}
As you can see, the class Node contains a variable member of type Node, to reference the next element of the linked list. Finally, a simplistic implementation of the linked list would be:
class LinkedList<T> {
private Node<T> first;
private Node<T> last;
private int length = 0;
public void add(T value) {
Node<T> node = new Node<T>(value);
if(length != 0) {
last.setNext(node);
last = node;
}
else {
first = node;
last = node;
}
length++;
}
public Node<T> getFirst() {
return first;
}
}
When a new node is added to the collection, the previous last node references it and therefore, becomes the new last node.

Need guidance on creating Node class (java)?

I need to implement a Node class, where the basic methods are: getItem(), getNext(), setItem() and setNext(). I want the nodes to be able to store at least the default integer range in Java as the “item”; the “next” should be a reference or pointer to the next Node in a linked list, or the special Node NIL if this is the last node in the list.I also want to implement a two-argument constructor which initializes instances with the given item (first argument) and next node (second argument) , I've kind of hit a brick wall and need some guidance about implementing this , any ideas ?
I have this so far:
class Node {
public Node(Object o, Node n) {
}
public static final Node NIL = new Node(Node.NIL, Node.NIL);
public Object getItem() {
return null;
}
public Node getNext() {
return null;
}
public void setItem(Object o) {
}
public void setNext(Node n) {
}
}
While implementing the custom LinkedList/Tree, we need Node. Here is demo of creating Node and LinkedList. I have not put in all the logic. Just basic skeleton is here and you can then add more on yourself.
I can give you a quick hint on how to do that:
Class Node{
//these are private class attributes, you need getter and setter to alter them.
private int item;
private Node nextNode;
//this is a constructor with a parameter
public Node(int item)
{
this.item = item;
this.nextNode = null;
}
// a setter for your item
public void setItem(int newItem)
{
this.item = newItem;
}
// this is a getter for your item
public int getItem()
{
return this.item;
}
}
You can create a Node object by calling:
Node newNode = Node(2);
This is not a complete solution for your problem, the two parameter constructor and the last node link are missing, but this should lead you in the correct direction.
Below is a simple example of the Node implementation, (i renamed Item to Value for readability purpose). It has to be implemented somehow like this, because methods signatures seems to be imposed to you. But keep in mind that this is definely not the best way to implement a LinkedList.
public class Node {
public static final Node NIL = null;
private Integer value;
private Integer next;
public Node(Integer value, Node next) {
this.value = value;
this.next = next;
}
public Integer getValue() {
return this.value;
}
public Node getNext() {
return this.next;
}
public void setValue(Integer value) {
this.value = value;
}
public void setNext(Node next) {
this.next = next;
}
public boolean isLastNode() {
return this.next == Node.NIL || Node;
}
}
public class App {
public static void main(String[] args) {
Node lastNode = new Node(92, Node.NIL);
Node secondNode = new Node(64, lastNode);
Node firstNode = new Node(42, secondNode);
Node iterator = firstNode;
do () {
System.out.println("node value : " + iterator.getValue());
iterator = iterator.getNext();
} while (iterator == null || !iterator.isLastNode());
}
}
The node class that will be implemented changes according to the linked list you want to implement. If the linked list you are going to implement is circular, then you could just do the following:
public class Node {
int data;
Node next = null;
public Node(int data){
this.data = data;
}
}
Then how are you going to implement the next node?
You are going to do it in the add method of the circularLinkedList class. You can do it as follows:
import java.util.*;
public class CircularLinkedList {
public CircularLinkedList() {}
public Node head = null;
public Node tail = null;
public void add(int data) {
Node newNode = new Node(data);
if(head == null) {
head = newNode;
}
else {
tail.next = newNode;
}
tail = newNode;
tail.next = head;
}
public void displayList() {
System.out.println("Nodes of the circular linked list: ");
Node current = head;
if(head == null) {
System.out.println("Empty list...");
}
else {
do {
System.out.print(" " + current.data);
current = current.next;
}while(current != head);
System.out.println();
}
}
}

Class cast exception while adding a second tree node to PriorityQueue

I am trying to print a binary tree by BFS.
my implementation is with a PriorityQueue.
in the beginning i insert root into PriorityQueue.
then in loop, i pull a node from PriorityQueue, print it, and insert his childs(if thay are not null) into PriorityQueue.
why when inserting the second node, i get this exception:
Exception in thread "main" java.lang.ClassCastException: Node cannot be cast to java.lang.Comparable
this is my code:
class main:
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Tree tree = new Tree();
}
}
class Node:
public class Node {
public Node(){}
public Node(int num)
{
value = num;
}
private int value;
private Node left;
private Node right;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
}
class tree:
public class Tree {
private Node root;
public Tree()
{
root = new Node(5);
Node node2 = new Node(2);
Node node10 = new Node(10);
Node node8 = new Node(8);
Node node6 = new Node(6);
Node node15 = new Node(15);
root.setRight(node10);
root.setLeft(node2);
node10.setRight(node15);
node10.setLeft(node8);
node8.setLeft(node6);
printToWidth(root);
}
public void printToWidth(Node node)
{
PriorityQueue<Node> queue = new PriorityQueue<Node>();
queue.add(node);
while( !(queue.isEmpty()))
{
Node n = queue.poll();
System.out.println(n.getValue());
if (n.getLeft() != null)
queue.add(n.getLeft());
if (n.getRight() != null)
queue.add(n.getRight());
}
System.out.println("end printToWidth");
}
}
You've got two options:
Make Node implement Comparable<Node>, so that the elements can be inserted according to their natural ordering. This is likely the easier of the two.
public int compareTo(Node other) {
return value - other.getValue();
}
Use a custom Comparator<Node> and supply a compare method there, with an initial capacity.
PriorityQueue<Node> queue = new PriorityQueue<Node>(10, new Comparator<Node>() {
public int compare(Node left, Node right) {
return left.getValue() - other.getValue();
}
});
The exception is telling you, make Node implement Comparable<Node>.
You can insert the first node because it has nothing to compare to, so the comparison is not needed.

java program printing weird hexadecimal output

Ok i am trying to write a program for binary search tree. Everything looks good except my program keeps printing this instead of just my inorder traversal of integers.I tried to just just println in the main method and got the same thing?
This is my code:
public class bst {
Node root;
public Node getRoot(){
return root;
}
public bst(){
root=null;
}
//method addNode
public void insert(int key){
Node newNode= new Node(key);//initialize Node
if(root==null){
root=newNode;
}else{
Node focusNode=root;
Node insNode=root;
while(insNode!=null){
focusNode=insNode;
if(key<focusNode.getKey()){
insNode=insNode.getLeft();
}
else{
insNode=insNode.getRight();
}
}
if(key<focusNode.getKey()){
focusNode.setLeft(newNode);
}
else{
focusNode.setRight(newNode);
}
}
}
public void inOrder(Node focusNode){
if (focusNode !=null){
inOrder(focusNode.leftChild);
System.out.println(focusNode);
inOrder(focusNode.rightChild);
}
}
//Node class
class Node{
int key;
Node leftChild;
Node rightChild;
//Node constructor
Node(int key){
this.key=key;
leftChild=null;
rightChild=null;
}
public void setLeft(Node left){
this.leftChild=left;
}
public void setRight(Node right){
this.rightChild=right;
}
public Node getLeft(){return leftChild;}
public Node getRight(){return rightChild;}
public void setKey(int k){this.key=k;}
public int getKey(){return key;}
public void print(){
System.out.println(getKey());
}
}
public static void main(String[] args){
bst theTree= new bst();
theTree.insert(30);
theTree.insert(60);
theTree.insert(50);
theTree.insert(70);
theTree.inOrder(theTree.getRoot());
}
}
In the inOrder method, you do:
System.out.println(focusNode);
You are printing focusNode directly, so unless your Node class overrides the default toString method you will just see a hash code of your object (see this question for details if you are interested). You probably wanted something like
System.out.println(focusNode.getKey());
or simply using the print method you wrote instead.
It looks like you are trying to print the actual Node, which will just be the memory address that of that node. If you want to print the the integers, you should print the key to the node.
print(node.getKey());

Categories