Finding the oldest element in a min priority queue java - java

I am supposed to return the oldest element in a priority min queue along with said element. I have to use nodes, arrays are optional. This is what I got so far but I have an null pointer error on line 20 and i don't know how to fix it. Please help
public class MinHeap {
public static int timeStamp = 0;
public static int ts = 0;
public static int maxTime = 0;
public static Node root;
public MinHeap(){
this.root = null;
}
public static void insert(int id, int ts){
timeStamp++;
Node newNode = new Node(id);
if(root==null){
root = newNode;
}
Node current = root;
Node parent = null;
while(true){
parent = current;
if(id < current.data){
current = current.left;
if(current==null){
parent.left = newNode;
}
}else{
current = current.right;
if(current==null){
parent.right = newNode;
}
}
}
}
public static Node delete(int x, Node n){
timeStamp++;
if(n==null)
return n;
if(x == n.data){
if(n.left == null && n.right == null){
return null;
}else if(n.left == null){
n.right = delete(x, n.right);
return n;
}else if(n.right == null){
n.left = delete(x, n.left);
return n;
}else{
Node tempNode = findMin(n.right);
n.right = delete(tempNode.data, n.right);
n.data = tempNode.data;
return n;
}
}
if(x < n.data){
n.left = delete(x, n.left);
return n;
}else{
n.right = delete(x, n.right);
return n;
}
}
public static void display(Node root){
if(root!=null){
display(root.left);
System.out.print(" " + root.data);
display(root.right);
}
}
public static Node findMin(Node n){
if(n == null){
return null;
}
if(n.left == null){
return n;
}
return findMin(n.left);
}
public static int maxAge(){
int currentAge = 0;
currentAge = timeStamp - ts;
if(currentAge > maxTime)
maxTime = currentAge;
return maxTime;
}
public static void main(String [] arg){
MinHeap min = new MinHeap();
min.insert(1, ts = 0);
min.insert(2, ts = 1);
min.insert(3, ts = 2);
min.insert(4, ts = 4);
min.delete(1, root);
min.delete(2, root);
min.delete(3, root);
min.delete(4, root);
min.maxAge();
}
}
class Node{
int data;
Node left;
Node right;
public Node(int data){
this.data = data;
left = null;
right = null;
}
}

Your insert is broken. You forgot to break after finding the insert point, and you're not checking for the case where the key is already in the tree.
while (true) {
parent = current;
if (id < current.data) {
current = current.left;
if (current == null) {
parent.left = newNode;
// Break after insert
break;
}
} else if (id > current.data) {
current = current.right;
if (current == null) {
parent.right = newNode;
// Break after insert
break;
}
} else {
// Key exists.
break;
}
}

Related

My insertion sort is not giving desired result and i am not able to figure out

i was trying to perform insertion sort on a doubly linked list and before anyone suggest that i should use sorted insertion i know it can be done but it is not allowed for the work.
here is the code:
import java.util.ArrayList;
public class DLinkedList {
private class Node {
private int value;
private Node nextNode;
private Node prevNode;
public Node(int v) {
value = v;
nextNode = null;
prevNode = null;
}
public int getValue() {
return value;
}
public void setValue(int v) {
value = v;
}
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node n) {
nextNode = n;
}
public Node getPrevNode() {
return prevNode;
}
public void setPrevNode(Node n) {
prevNode = n;
}
}
// Holds a reference to the head and tail of the list
private Node headNode;
private Node tailNode;
public DLinkedList() {
headNode = null;
tailNode = null;
}
public Object getHeadValue() {
if (headNode == null)
return null;
return headNode.value;
}
public Object getTailValue() {
if (tailNode == null)
return null;
return tailNode.value;
}
public void addAtHead(int o) {
Node newNode = new Node(o);
newNode.setNextNode(headNode);
if (headNode != null)
headNode.setPrevNode(newNode);
headNode = newNode;
// special case for empty list
if (tailNode == null)
tailNode = newNode;
}
public void addAtTail(int o) {
Node newNode = new Node(o);
// this means that headNode == null too!
if (tailNode == null) {
tailNode = newNode;
headNode = newNode;
} else {
newNode.setPrevNode(tailNode);
tailNode.setNextNode(newNode);
tailNode = newNode;
}
}
public int deleteAtHead() {
// list is empty
if (headNode == null) {
headNode = null;
tailNode = null;
return -1;
}
// singleton: must update tailnode too
if (headNode == tailNode) {
int res = headNode.getValue();
headNode = null;
tailNode = null;
return res;
}
int res = headNode.getValue();
headNode = headNode.getNextNode();
headNode.setPrevNode(null);
return res;
}
public int deleteAtTail() {
// list is empty
if (tailNode == null) {
headNode = null;
tailNode = null;
return -1;
}
// singleton: must update tailnode too
if (headNode == tailNode) {
int res = tailNode.getValue();
headNode = null;
tailNode = null;
return res;
}
int res = tailNode.getValue();
tailNode = tailNode.getPrevNode();
tailNode.setNextNode(null);
return res;
}
public int delete(Node n) {
if (n == null)
return -1;
Node next = n.getNextNode();
Node prev = n.getPrevNode();
int val = n.getValue();
if (prev != null)
prev.setNextNode(next);
if (next != null)
next.setPrevNode(prev);
// deleting at the end
if (n == tailNode)
tailNode = prev;
// deleteing at beginning
if (n == headNode)
headNode = next;
return val;
}
public void insertAfter(Node n, int val) {
if (n == null) { // this is the headNode
addAtHead(val);
return;
}
Node next = n.getNextNode();
Node newNode = new Node(val);
newNode.setPrevNode(n);
newNode.setNextNode(next);
n.setNextNode(newNode);
if (next == null) { // insert at tail
tailNode = newNode;
} else {
next.setPrevNode(newNode);
}
}
// computes the size of the list
public int size() {
if (headNode == null)
return 0;
Node n = headNode;
int size = 0;
while (n != null) {
size++;
n = n.getNextNode();
}
return size;
}
// Predicate to check if the linked list is sorted
public boolean isSorted() {
if (headNode == null || headNode.nextNode == null)
return true;
Node i = headNode.nextNode;
while (i != null) {
if (i.getValue() < i.getPrevNode().getValue())
return false;
i = i.nextNode;
}
return true;
}
// toString methods to override printing of object
public String toString() {
Node n = headNode;
StringBuffer buf = new StringBuffer();
while (n != null) {
buf.append(n.getValue());
buf.append(" ");
n = n.getNetNode();
}
return buf.toString();
}
public void insertionSort(DLinkedList arr) {
Node current=arr.headNode.getNextNode();
while(current!=null)
{
Node nextNode=current.getNextNode();
Node searchNode=current.prevNode;
while(searchNode!=null && searchNode.getValue()>current.getValue())
{
searchNode=searchNode.prevNode;
}
delete(current);
if(searchNode==null) {
current.prevNode=null;
addAtHead(current.getValue());
}
else {
insertAfter(searchNode,searchNode.getValue());
}
current=nextNode;
}
}
public static void main(String[] args) {
DLinkedList d = new DLinkedList();
d.addAtHead(4);
d.addAtHead(1);
d.addAtHead(7);
d.addAtHead(10);
d.addAtHead(101);
System.out.println("Before sorting: " + d); // this will call the toString method
d.insertionSort(d);
System.out.println("After sorting: " + d);
}
}
the list i provided is 101 10 7 1 4
and the list after sorting comes 1 1 7 10 101
i have been scratching my head for days but can't figure it out
Function you all need to look at is
public void insertionSort(DLinkedList arr)

Java AVL tree pointer manipulation

I'm having trouble implementing an AVL tree in java and would appreciate your help,
preferably by explaining what's wrong with my code (I've seen different implementations and would like to figure out what's wrong with mine).
public class AVLTree<T> {
public AVLNode<T> root;
int size;
//constructor
public AVLTree() {
root = null;
size = 0;
}
public void add(T obj) {
//initialize the new node
AVLNode<T> node = new AVLNode<T>(obj);
//if the tree is empty than our new node will serve as a root
if(root == null)
{
root = node;
size++;
return;
}
add(root, node);
}
private void checkViolations(AVLNode<T> node) {
int dif = Math.abs(height(node.left) - height(node.right)) ;
//there's a violation at our level
if(dif > 1)
{
rebalance(node);
}
//if we're at the root, tree is balances(AVL)
if(node.parent == null) return;
//we're not at the top, check parent
checkViolations(node.parent);
}
private void rebalance(AVLNode<T> node) {
//right subtree is bigger than left subtree
if(height(node.right) - height(node.left) > 1)
{
//problem is right-right
if(height(node.right.right) > height(node.right.left))
node = leftRotation(node);
//problem is right-left
else
node = rightLeftRotation(node);
}
//left subtree is bigger than right subtree
else
{
//problem is left-left
if (height(node.left.left) > height(node.left.right))
node = rightRotation(node);
//problem is left-right
else
node = leftRightRotation(node);
}
if (node.parent == null)
root = node;
}
private AVLNode<T> rightLeftRotation(AVLNode<T> node) {
node.right = rightRotation(node.right);
return leftRotation(node);
}
private AVLNode<T> leftRightRotation(AVLNode<T> node){
node.left = leftRotation(node.left);
return rightRotation(node);
}
private AVLNode<T> rightRotation(AVLNode<T> node) {
AVLNode<T> temp = node.left;
node.left = temp.right;
temp.parent = node.parent;
temp.right = node;
node.parent = temp;
return temp;
}
private AVLNode<T> leftRotation(AVLNode<T> node) {
AVLNode<T> temp = node.right;
node.right = temp.left;
temp.parent = node.parent;
temp.left = node;
node.parent = temp;
return temp;
}
private int height(AVLNode<T> node) {
//base case
if(node == null) return 0;
return 1 + (Math.max(height(node.left), height(node.right)));
}
private void add(AVLNode<T> parent, AVLNode<T> newNode) {
if(((Comparable<T>)newNode.data).compareTo(parent.data) > 0)
{
if(parent.right == null)
{
parent.right = newNode;
newNode.parent = parent;
size++;
}
else add(parent.right, newNode);
}
else
{
if(parent.left == null)
{
parent.left = newNode;
newNode.parent = parent;
size++;
}
else add(parent.left, newNode);
}
checkViolations(newNode);
}
}
I'm trying to add the next numbers in this order (left to right): 1,2,3,4,5
up until 4, everything seems to go great.
Thank you

Sorting doubly linked list in java using insertion sort

I am trying to use insertion sort to sort a doubly linked list. Before sorting, the doubly linked list has the following elements in the following order: 4, 1, 7, 10. The output it supposed to be 1, 4, 7, 10 (basically use the insertionSort method to sort the elements in ascending order).
delete - deletes a node and returns its value
insertAfter(Node n, val v) - inserts a new node with value v after node n
I've tried researching but haven't found anything to solve this.
Can anyone please help me?
import java.util.ArrayList;
public class DLinkedList {
private class Node {
private int value;
private Node nextNode;
private Node prevNode;
public Node(int v) {
value = v;
nextNode = null;
prevNode = null;
}
public int getValue() {
return value;
}
public void setValue(int v) {
value = v;
}
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node n) {
nextNode = n;
}
public Node getPrevNode() {
return prevNode;
}
public void setPrevNode(Node n) {
prevNode = n;
}
}
// Holds a reference to the head and tail of the list
private Node headNode;
private Node tailNode;
public DLinkedList() {
headNode = null;
tailNode = null;
}
public void addAtHead(int o) {
Node newNode = new Node(o);
newNode.setNextNode(headNode);
if (headNode != null)
headNode.setPrevNode(newNode);
headNode = newNode;
// special case for empty list
if (tailNode == null)
tailNode = newNode;
}
public void addAtTail(int o) {
Node newNode = new Node(o);
// this means that headNode == null too!
if(tailNode == null){
tailNode = newNode;
headNode = newNode;
}else{
newNode.setPrevNode(tailNode);
tailNode.setNextNode(newNode);
tailNode = newNode;
}
}
public int deleteAtHead() {
// list is empty
if(headNode == null){
headNode = null;
tailNode = null;
return -1;
}
// singleton: must update tailnode too
if(headNode == tailNode){
int res = headNode.getValue();
headNode = null;
tailNode = null;
return res;
}
int res = headNode.getValue();
headNode = headNode.getNextNode();
headNode.setPrevNode(null);
return res;
}
public int deleteAtTail() {
// list is empty
if(tailNode == null){
headNode = null;
tailNode = null;
return -1;
}
// singleton: must update tailnode too
if(headNode == tailNode){
int res = tailNode.getValue();
headNode = null;
tailNode = null;
return res;
}
int res = tailNode.getValue();
tailNode = tailNode.getPrevNode();
tailNode.setNextNode(null);
return res;
}
public int delete(Node n) {
if (n == null)
return -1;
Node next = n.getNextNode();
Node prev = n.getPrevNode();
int val = n.getValue();
if (prev != null)
prev.setNextNode(next);
if (next != null)
next.setPrevNode(prev);
// deleting at the end
if (n == tailNode)
tailNode = prev;
// deleteing at beginning
if (n == headNode)
headNode = next;
return val;
}
public void insertAfter(Node n, int val) {
if (n == null) { // this is the headNode
addAtHead(val);
return;
}
Node next = n.getNextNode();
Node newNode = new Node(val);
newNode.setPrevNode(n);
newNode.setNextNode(next);
n.setNextNode(newNode);
if (next == null) { // insert at tail
tailNode = newNode;
} else {
next.setPrevNode(newNode);
}
}
// computes the size of the list
public int size() {
if (headNode == null)
return 0;
Node n = headNode;
int size = 0;
while (n != null) {
size++;
n = n.getNextNode();
}
return size;
}
// Predicate to check if the linked list is sorted
public boolean isSorted() {
if (headNode == null || headNode.nextNode == null)
return true;
Node i = headNode.nextNode;
while (i != null) {
if (i.getValue() < i.getPrevNode().getValue())
return false;
i = i.nextNode;
}
return true;
}
// toString methods to override printing of object
public String toString() {
Node n = headNode;
StringBuffer buf = new StringBuffer();
while (n != null) {
buf.append(n.getValue());
buf.append(" ");
n = n.getNextNode();
}
return buf.toString();
}
public static void main(String[] args) {
DLinkedList d = new DLinkedList();
d.addAtHead(4);
d.addAtHead(1);
d.addAtHead(7);
d.addAtHead(10);
System.out.println("Before sorting: " + d); // this will call the toString method
d.insertionSort();
System.out.println("After sorting: " + d);
}
}
So if you want the list to be sorted why go with sorting at the end ? What I prefer is to insert them in the sorted way. So each time an element is inserted, its inserted in a sorted form.
Here is the working code:
import java.util.ArrayList;
public class DLinkedList {
private class Node {
private int value;
private Node nextNode;
private Node prevNode;
public Node(int v) {
value = v;
nextNode = null;
prevNode = null;
}
public int getValue() {
return value;
}
public void setValue(int v) {
value = v;
}
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node n) {
nextNode = n;
}
public Node getPrevNode() {
return prevNode;
}
public void setPrevNode(Node n) {
prevNode = n;
}
}
// Holds a reference to the head and tail of the list
private Node headNode;
private Node tailNode;
public DLinkedList() {
headNode = null;
tailNode = null;
}
public void addAtHead(int o) {
Node newNode = new Node(o);
newNode.setNextNode(headNode);
if (headNode != null)
headNode.setPrevNode(newNode);
headNode = newNode;
// special case for empty list
if (tailNode == null)
tailNode = newNode;
}
public void addAtTail(int o) {
Node newNode = new Node(o);
// this means that headNode == null too!
if(tailNode == null){
tailNode = newNode;
headNode = newNode;
}else{
newNode.setPrevNode(tailNode);
tailNode.setNextNode(newNode);
tailNode = newNode;
}
}
public int deleteAtHead() {
// list is empty
if(headNode == null){
headNode = null;
tailNode = null;
return -1;
}
// singleton: must update tailnode too
if(headNode == tailNode){
int res = headNode.getValue();
headNode = null;
tailNode = null;
return res;
}
int res = headNode.getValue();
headNode = headNode.getNextNode();
headNode.setPrevNode(null);
return res;
}
public int deleteAtTail() {
// list is empty
if(tailNode == null){
headNode = null;
tailNode = null;
return -1;
}
// singleton: must update tailnode too
if(headNode == tailNode){
int res = tailNode.getValue();
headNode = null;
tailNode = null;
return res;
}
int res = tailNode.getValue();
tailNode = tailNode.getPrevNode();
tailNode.setNextNode(null);
return res;
}
public int delete(Node n) {
if (n == null)
return -1;
Node next = n.getNextNode();
Node prev = n.getPrevNode();
int val = n.getValue();
if (prev != null)
prev.setNextNode(next);
if (next != null)
next.setPrevNode(prev);
// deleting at the end
if (n == tailNode)
tailNode = prev;
// deleteing at beginning
if (n == headNode)
headNode = next;
return val;
}
public void insertAfter(Node n, int val) {
if (n == null) { // this is the headNode
addAtHead(val);
return;
}
Node next = n.getNextNode();
Node newNode = new Node(val);
newNode.setPrevNode(n);
newNode.setNextNode(next);
n.setNextNode(newNode);
if (next == null) { // insert at tail
tailNode = newNode;
} else {
next.setPrevNode(newNode);
}
}
// computes the size of the list
public int size() {
if (headNode == null)
return 0;
Node n = headNode;
int size = 0;
while (n != null) {
size++;
n = n.getNextNode();
}
return size;
}
// Predicate to check if the linked list is sorted
public boolean isSorted() {
if (headNode == null || headNode.nextNode == null)
return true;
Node i = headNode.nextNode;
while (i != null) {
if (i.getValue() < i.getPrevNode().getValue())
return false;
i = i.nextNode;
}
return true;
}
// toString methods to override printing of object
public String toString()
{
Node n = headNode;
StringBuffer buf = new StringBuffer();
while (n != null) {
buf.append(n.getValue());
buf.append(" ");
n = n.getNextNode();
}
return buf.toString();
}
// Insert in sorted for so you dont have to sort it after words
public void sortedInsert(int insertItem){
Node newNode = new Node(insertItem);
if(headNode == null){
headNode = tailNode = newNode;
return;
}
else {
Node temp = new Node(insertItem);
Node current = headNode;
while((current != null) && current.getValue() < insertItem){
temp = current;
current = current.getNextNode();
}
if(current == headNode){
addAtHead(insertItem);
return;
}
if (current == null){
addAtTail(insertItem);
return;
}
temp.setNextNode(newNode);
newNode.setNextNode(current);
current.setPrevNode(newNode);
newNode.setPrevNode(temp);
}
}
public static void main(String[] args) {
DLinkedList d = new DLinkedList();
String beforeSort = "";
d.sortedInsert(4);
// you can add the number in the order they are inserted just to show what it will look like unsorted
beforeSort+=" 4";
d.sortedInsert(1);
beforeSort+=" 1";
d.sortedInsert(7);
beforeSort+=" 7";
d.sortedInsert(10);
beforeSort+=" 10";
System.out.println("Before sorting: " + beforeSort);
System.out.println("After sorting: " + d); // this will call the toString method
}
}

How can I delete any node at random out of a Doubly Linked List in Java?

I'm making a Doubly Linked List that allows you to insert at the front and rear, as well as deleting any node from the list as long as it exists. The problem is that it doesn't work and gives off and either gives off a NullPointerException or it just says That Integer does not exist even though it does exist.The code is:
public class Numbers {
Node head = null; //Head of the list
Node tail = null; //end of the doubly list
int size = 0;
public void FrontInsert(int data) {
Node n = new Node();
if (head == null) {
head = n;
} else {
n.prev = head;
head.next = n;
head = n;
}
size++;
}
public void RearInsert(int data) {
Node n = new Node();
if (head == null) {
head = n;
tail = n;
} else {
n.next = tail;
tail.prev = n;
tail = n;
}
size++;
}
public void Delete(int x) {
if (size == 0) {
System.out.println("The list is empty.");
}
if (head.data == x) {
head = head.next;
if (head != null) {
head.prev = null;
}
size--;
return;
}
tmp = head;
while (tmp != null && tmp.data != x) {
tmp = tmp.next;
}
if (tmp == null) {
System.out.println("That integer does not exist.");
return;
}
if (tmp.data == x) {
tmp.prev.next = tmp.next;
if (tmp.next != null) {
tmp.next.prev = tmp.prev;
}
}
size--;
}
public void printList() {
while (head != null) {
System.out.print(head.data + " ");
head = head.prev;
}
}
public static void main(String[] args) {
Numbers nu = new Numbers();
}
class Node {
Node prev;
Node next;
int data;
public void Node(int data) {
this.data = data;
next = null;
prev = null;
}
}
}
Try this and check output
public class Numbers {
Node head = null;
Node tail = null;
int size = 0;
public void FrontInsert(int data) {
Node n = new Node(data);
if (head == null) { // first insert
head = n;
tail = n;
} else {
n.next = head;
head.prev = n;
head = n;
}
size++;
}
public void RearInsert(int data) {
Node n = new Node(data);
if (head == null) {
head = n;
tail = n;
} else {
n.prev = tail;
tail.next = n;
tail = n;
}
size++;
}
public void Delete(int index) { // index is the position to be remove
if (size == 0) {
System.out.println("The list is empty."); return;
}else if(index < 0 || index > size -1){
System.out.println("Index outOf Bound."); return;
}
Node currentNode = head;
for(int i = 1; i <= index ; i++){
currentNode = currentNode.next;
}
//remove
if (index == 0) {
currentNode.next.prev = null;
head = currentNode.next;
} else if (index == size - 1) {
currentNode.prev.next = null;
tail = currentNode.prev;
} else {
if (currentNode.prev != null) // Ensure its not header
currentNode.prev.next = currentNode.next;
if (currentNode.next != null) // Ensure its not tail
currentNode.next.prev = currentNode.prev;
}
size--;
}
public void printList() {
Node tmp = head;
while (tmp != null) {
System.out.print(tmp.data + " ");
tmp = tmp.next;
}
System.out.println();
}
public static void main(String[] args) {
Numbers nu = new Numbers();
nu.FrontInsert(1);nu.printList();
nu.FrontInsert(2);nu.printList();
nu.RearInsert(3);nu.printList();
nu.FrontInsert(4);nu.printList();
nu.RearInsert(3);nu.printList();
nu.FrontInsert(4);nu.printList();
nu.RearInsert(3);nu.printList();
nu.RearInsert(3);nu.printList();
nu.FrontInsert(4);nu.printList();
System.out.println();
nu.Delete(4);
nu.printList();
}
class Node {
Node prev;
Node next;
int data;
public Node(int data) {
this.data = data;
next = null;
prev = null;
}
}
}
Well, your head and tail were mutually exclusive, i mean when you add something to the tail of the list, you were only giving one side reference not both side, you have to says
tail.next = n; n.prev = tail; and tail = n.
Here is a working code:
public class Numbers {
Node head = null; //Head of the list
Node tail = null; //end of the doubly list
int size = 0;
public void FrontInsert(int data) {
Node n = new Node(data);
if (head == null) {
head = n;
tail = head;
} else {
n.next = head;
head.prev = n;
head = n;
}
size++;
}
public void RearInsert(int data) {
Node n = new Node(data);
if (head == null) {
head = n;
tail = head;
} else {
n.next = null;
tail.next = n;
n.prev = tail;
tail = n;
}
size++;
}
#SuppressWarnings("null")
public void Delete(int x) {
if (size == 0) {
System.out.println("The list is empty.");
return;
}
if (head.data == x) {
head = head.next;
if (head != null) {
head.prev = null;
}
size--;
return;
}
Node tmp = head;
while (true) {
if(tmp == null)
break;
if(tmp.data == x)
break;
System.out.println(tmp.data);
tmp = tmp.next;
}
if (tmp == null) {
System.out.println("That integer does not exist.");
return;
}
if (tmp.data == x) {
tmp.prev.next = tmp.next;
if (tmp.next != null) {
tmp.next.prev = tmp.prev;
}
}
size--;
}
public void printList() {
while (head != null) {
System.out.print(head.data + " ");
head = head.next;
}
}
public static void main(String[] args) {
Numbers nu = new Numbers();
nu.FrontInsert(2);
nu.FrontInsert(3);
nu.FrontInsert(6);
nu.RearInsert(8);
nu.RearInsert(20);
nu.Delete(8);
nu.printList();
// System.out.println(nu.head.data + "data");
// System.out.println(nu.head.next.data + "data");
}
class Node {
Node prev;
Node next;
private int data;
public Node(int data) {
this.data = data;
next = null;
prev = null;
}
}
}

Counting nodes in a BST

folks, I've implemented the code for counting the total number of Nodes in a binary tree and the method looks like the following:
public int countNodes(Node root){
int count = 0;
if(root == null){
System.out.println("The tree is empty!");
return -1;
}
else{
count = 1;
Node current = root;
if(current.leftChild != null){
count += countNodes(current.leftChild);
}
else if(current.rightChild != null){
count += countNodes(current.rightChild);
}
}
System.out.print("The total number of nodes in the tree is ");
return count;
}
The parameter of the method contains Node root but my question is when I try to run the method from the main class then what should I pass as a parameter??
what should I add inside the parameters here?:
int countNodes = tree1.countNodes("?????????????");
package BST;
public class Node {
int data;
Node leftChild;
Node rightChild;
public void displayNode(){
System.out.println("The data is " + this.data);
}
}
class Tree{
private Node root;
public Tree(){
this.root = null;
}
public Node find(int key){
Node current = root;
while(current.data != key){
if(key < current.data){
current = root.leftChild;
}
else{
current = root.rightChild;
}
if(current == null){
System.out.println("The Node contatining the key " + key + " does not exist!");
return null;
}
}
return current;
}
public void insert(int key){
Node newNode = new Node();
if(root == null){
root = newNode;
}
else{
Node current = root;
Node parent;
while(true){
parent = current;
if(current.data > key){
current = current.leftChild;
if(current == null){
parent.leftChild = newNode;
return;
}
}
else{
current = current.rightChild;
if(current == null){
parent.rightChild = newNode;
return;
}
}
}
}
}
public Node findMin(){
if(root == null){
System.out.println("The tree is empty!");
return null;
}
else{
Node current = root.leftChild;
Node last = root;
while(current != null){
last = current;
current = current.leftChild;
}
return last;
}
}
public Node findMax(){
if(root == null){
System.out.println("The tree is empty!");
return null;
}
else{
Node current = root.rightChild;
Node last = root;
while(current != null){
last = current;
current = current.rightChild;
}
return last;
}
}
public int countNodes(Node root){
int count = 0;
if(root == null){
System.out.println("The tree is empty!");
return -1;
}
else{
count = 1;
Node current = root;
if(current.leftChild != null){
count += countNodes(current.leftChild);
}
else if(current.rightChild != null){
count += countNodes(current.rightChild);
}
}
System.out.print("The total number of nodes in the tree is ");
return count;
}
Class MainTester
class MainTester{
public static void main(String[] args){
Tree tree1 = new Tree();
tree1.insert(1);
tree1.insert(2);
tree1.insert(3);
tree1.insert(4);
tree1.insert(5);
tree1.insert(6);
tree1.insert(7);
tree1.insert(8);
tree1.insert(9);
tree1.insert(10);
int countNodes = tree1.countNodes("?????????????");
}
}
You can use the root node of the tree. Basing from your example, you can get it from the method find()
int countNodes = tree1.countNodes(tree1.find(1));
You can also use other nodes like
int countNodes = tree1.countNodes(tree1.find(5));

Categories