Implementation of BInary Tree in java - java

I am trying to implement Binary tree in java and here is my code:
class TestClass {
public static void newnode(int a , Node root,){
root = new Node(a);
System.out.println(root.data); // Printing out 22
}
public static void main(String args[] ) throws IOException {
Node root = null;
newnode(22,root);
System.out.println(root.data); // Giving NullPointerException
}
}
class Node{
Node left ;
Node Right;
int data ;
Node(int dataa){
this.data = dataa;
}
}
I could not insert a new node in my tree , the value of root does not changesWhen i call newnode function I getting the correct value of my Root Node but in the main function it gives me null point exceptionWhy the value of root is not updating

class TestClass {
public static Node newnode(int a , Node root){
root = new Node(a);
System.out.println(root.data); // Printing out 22
return root;
}
public static void main(String args[] ) throws IOException {
Node root = null;
root = newnode(22,root);
System.out.println(root.data); // Giving NullPointerException
}
}
try this

You shouldn't design methods with a lot of input parameters, because testing will be more painful. Also, there is no need to pass null to method just to assign an object to it - this is poor design.
import java.io.IOException;
class TestClass {
// This method is useless, use Factory Design Pattern if you want
// to create such solution with multiple variants
public static Node newNode(int a) {
return new Node(a);
}
public static void main(String args[]) throws IOException {
Node root = newNode(22);
System.out.println(root.getData());
}
}
class Node {
private int data;
private Node left;
private Node right;
public Node(int data) {
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
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;
}
}

Related

Binary Tree in Java - why do i have an "empty" node (with a blank String) in my Tree?

Basically, my problem with my code is that somewhere in its implementation it creates a blank node which is then inserted into my binary tree. This node exists, as my sizeOfTree method counts it as such.
The code works just fine, the only problem is the node.
OK, so here I have defined the TreeNode based on which the Binary Tree is constructed:
package hr.fer.oop.lab1.prob6;
public class TreeNode {
TreeNode left=null;
TreeNode right=null;
String data;
public TreeNode(String data) {
this.data=data;
}
}
And here is the rest of it:
package hr.fer.oop.lab1.prob6;
import hr.fer.oop.lab1.prob6.TreeNode;
public class BinaryTree {
TreeNode root;
public BinaryTree() {
TreeNode node = new TreeNode("");
root=node;
}
public void insert (String data) {
if (this.root==null) {
this.root=new TreeNode(data);
return;
}
else {
TreeNode node = this.root;
TreeNode parent = new TreeNode("");
while(node!=null) {
parent = node;
if (node.data.compareTo(data)<=0) {
node=node.left;
}
else{
node=node.right;
}
}
if (parent.data.compareTo(data)<=0) {
parent.left=new TreeNode(data);
}
else {
parent.right=new TreeNode(data);
}
}
return;
}
private boolean subTreeContainsData(TreeNode node, String data) {
if ((node.data).compareTo(data)<1E-15) return true;
TreeNode temp=new TreeNode("");
temp=node;
if((temp.left.data).equals("")&&(temp.right.data).equals("")) return false;
return (subTreeContainsData(temp.left, data)||subTreeContainsData(temp.right, data));
}
private boolean containsData(String data) {
return subTreeContainsData(root, data);
}
private int sizeOfSubTree(TreeNode node) {
if (node==null) return 0;
return 1 + sizeOfSubTree(node.left) + sizeOfSubTree(node.right);
}
public int sizeOfTree() {
return sizeOfSubTree(root);
}
private void writeSubTree(TreeNode node) {
if (node!=null) {
writeSubTree(node.left);
System.out.println(node.data);
writeSubTree(node.right);
}
return;
}
public void writeTree() {
writeSubTree(root);
}
private void reverseSubTreeOrder(TreeNode node) {
if (node==null) return;
TreeNode helpNode;
helpNode=node.left;
node.left=node.right;
node.right=helpNode;
reverseSubTreeOrder(node.left);
reverseSubTreeOrder(node.right);
}
public void reverseTreeOrder() {
reverseSubTreeOrder(root);
}
public static void main (String[] args) {
BinaryTree tree = new BinaryTree();
tree.insert("Jasna");
tree.insert("Ana");
tree.insert("Ivana");
tree.insert("Anamarija");
tree.insert("Vesna");
tree.insert("Kristina");
System.out.println("Writing tree inorder:");
tree.writeTree();
tree.reverseTreeOrder();
System.out.println("Writing reversed tree inorder:");
tree.writeTree();
int size=tree.sizeOfTree();
System.out.println("Number of nodes in tree is "+size+".");
boolean found = tree.containsData("Ivana");
System.out.println("Searched element is found: "+found);
}
}
Much appreciate any help provided.
You create an empty TreeNode in your constructor and make it the root of the tree:
public BinaryTree() {
TreeNode node = new TreeNode("");
root=node;
}
Later, in your insert method, your if (this.root==null) condition is always false, so you don't assign the first inserted node to the root.
Just remove it:
public BinaryTree() {
}

Binary Tree printing out all zero's

When I print out the elements of this Binary Tree using my inOrder method, it prints: 0 0 0 0 0 0
Here is my Code:
public class BST {
class Node {
int data;
Node left;
Node right;
public Node(int data) {
data = data;
left = null;
right = null;
}
public Node root;
/**
* Method to insert a new node in order
* in our binary search tree
*/
public void insert(int data) {
root = insert(root, data);
}
public Node insert(Node node, int data){
if(node==null){
node = new Node(data);
}else if (data < node.data){
node.left = insert(node.left, data);
}else{
node.right = insert(node.right, data);
}
return node;
}
/**
Prints the node values in the "inorder" order.
*/
public void inOrder() {
inOrder(root);
}
private void inOrder(Node node) {
if (node == null)
return;
inOrder(node.left());
System.out.print(node.data + " ");
inOrder(node.right);
}
}
Main class:
public class Main {
public static void main(String[] args) {
BST tree = new BST();
tree.insert(6);
tree.insert(4);
tree.insert(8);
tree.insert(2);
tree.insert(1);
tree.insert(5);
tree.inOrder();
}
}
I have a feeling that it is something wrong in my insert method, I just can't figure out what. Any help in the right direction would be great, and sorry for being a noob!
In class Node your constructor is setting the constructor argument to itself instead of initializing the class variable.
Use the keyword this in your ctor to distinguish from constructor arguments and class variable.
Example:
public class Pair
{
private int left;
private int right;
public Pair(int left, int right) {
// the following 2 lines don't do anything
// it set's the argument "left = left" which is silly...
left = left;
right = right;
// with the `this` keyword we can correctly initialize our class properties
// and avoid name collision
this.left = left;
this.right = right;
}
}

K-Ary Tree Implementation in Java: how to?

I've a university project about creating two classes, Tree class and Node class, to implement a k-ary tree using Java.
In the class Tree, there should be a constructor which recives as input an int that indicates the tree arity.
I've worked before with general trees and this was my result:
Class tree: *
Class node: *
I absolutely don't know where and how to start to build this project (as I don't know how to manage the arity, maybe with ArrayList?).
Any advice and suggestions will be greatly appreciated :)
Thanks in advance.
Here are the new versions of the classes, with the methods that you needed.
Node:
import java.util.ArrayList;
import java.util.List;
public class Node {
public Node parent; // The parent of the current node
public List<Node> children; // The children of the current node
public Object info;
public static int maxNrOfChildren; // Equal to the k-arity;
public Node (Object info)
{
this.info=info;
children = new ArrayList<Node>(maxNrOfChildren);
}
public void addChild(Node childNode, int position)
// You must take care so that future insertions don't override a child on i-th position
{
if(position>=maxNrOfChildren-1)
{
// Throw some error
}
else
{
System.out.println("this.children="+this.children);
if(this.children.get(position)!=null)
{
// There is alerady a child node on this position; throw some error;
}
else
{
childNode.parent=this;
this.children.set(position, childNode);
}
}
}
}
Tree:
import java.util.ArrayList;
import java.util.List;
public class Tree {
public Node root;
public Tree(int kArity)
{
Node.maxNrOfChildren=kArity;
}
public void addRoot(Object info)
{
root=new Node(info);
root.parent=null;
root.children=new ArrayList<Node>(Node.maxNrOfChildren);
}
public void addNewNodeVasithChildOfNodeU(Node u, Object info, int i)
{
Node child=new Node(info);
u.addChild(child, i);
}
// I've made the above two methods of type void, not Node, because
// I see no reason in returning anything; however, you can override by calling
//'return root;' or 'return child;'
public int numberOfNodesInTree(Node rootNode){
int count=0;
count++;
if(rootNode.children.size()!=0) {
for(Node ch : rootNode.children)
count=count+numberOfNodesInTree(ch);
}
return count;
}
public int numberOfNodesInTree()
{
return numberOfNodesInTree(this.root);
}
public void changeRoot(Node newRoot, int i)
{
Node oldRoot=this.root;
newRoot.parent=null;
newRoot.addChild(oldRoot, i);
oldRoot.parent=newRoot;
this.root=newRoot;
}
public static void main(String args[])
{
Tree tree=new Tree(3);
Node a = new Node("a");
Node b = new Node("b");
Node c = new Node("c");
tree.addRoot("root");
tree.root.addChild(a,0);
a.addChild(b,0);
tree.root.addChild(c,1);
System.out.println(tree.numberOfNodesInTree(tree.root));
}
}
The logic is correct, but I am getting some Java-related error when I run the main method and I haven't yet figured out what the problem is.
this can be a starting point:
Node Class
import java.util.ArrayList;
import java.util.List;
public class Node {
public Node parent;//the parent of the current node
public List<Node> children = new ArrayList<Node>();//the children of the current node
public String name;//or any other property that the node should contain, like 'info'
public static int maxNrOfChildren;//equal to the k-arity;
public Node (String nodeName)
{
name=nodeName;
}
public void addChild(Node childNode)
{
if(this.children.size()>=maxNrOfChildren)
{
//do nothing (just don't add another node), or throw an error
}
else
{
childNode.parent=this;
this.children.add(childNode);
}
}
}
Tree Class
import java.util.ArrayList;
import java.util.List;
public class Tree {
public Node root = new Node("root");
public Tree(int kArity)
{
Node.maxNrOfChildren=kArity;
root.parent=null;
}
public void traverseTree(Node rootNode)//depth first
{
System.out.println(rootNode.name);
if(rootNode.children.size()!=0)
for(Node ch : rootNode.children)
traverseTree(ch);
}
public static void main(String args[])
{
Tree tree=new Tree(3);
Node a = new Node("a");
Node b = new Node("b");
Node c = new Node("c");
tree.root.addChild(a);
a.addChild(b);
tree.root.addChild(c);
tree.traverseTree(tree.root);
}
}
Please give further details about your project specifications, otherwise i can't figure out which kind of functionality you need within these classes
The idea behind creating a k-array, is that this is not a conventional structure like a list or a set, the node is like an element in a linked list, it point to the n other child node and can also point to the parent, whant determine what should be the child or the parent in that sctructure is an entire different question. As for the list of child in the node you can use any structure you whant ArrayList most likely will be a good fit. The choice of a structure depend on many factors like size, how often it will be accessed does it need to be sorted etc.
Have a look at this. Hope it helps.
import java.util.ArrayList;
public class Nary
{
public static Node root;
public static int insert(Node rootNode, int parentId, ArrayList<Node> nodeToAdd)
{
if(rootNode == null)
return 0;
if(rootNode.children == null)
rootNode.children = new ArrayList<Node>();
if(rootNode.id == parentId)
{
for(int i =0; i < nodeToAdd.size(); i++)
{
Node node = nodeToAdd.get(i);
node.parent = rootNode;
rootNode.children.add(node);
}
return 1;
}
else
{
for(int i = 0; i < rootNode.children.size(); i++)
{
int resultFlag = insert(rootNode.children.get(i), parentId, nodeToAdd);
if(resultFlag == 1)
{
return 1;
}
}
}
return -1;
}
public static void traverse(Node root)
{
if(root == null)
{
return;
}
System.out.println(root.data + " " + root.id );
for(Node child : root.children)
{
traverse(child);
}
}
public static void main(String[] args) {
// Insertion
root = new Node(0, "root");
int parentId = root.id;
Node Bread = new Node(1, "Bread");
Node Milk = new Node(2, "Milk");
Node Meat = new Node(3, "Meat");
Node Eggs = new Node(4, "Eggs");
ArrayList<Node> nodeList = new ArrayList<Node>();
nodeList.add(Bread);
nodeList.add(Milk);
nodeList.add(Meat);
nodeList.add(Eggs);
insert(root, parentId, nodeList);
// Add children for Bread
parentId = Bread.id;
Node Bread0 = new Node(11, "Whole-Wheat");
Node Bread1 = new Node(12, "Whole-Grain");
Node Bread2 = new Node(13, "Italian");
ArrayList<Node> nodeList1 = new ArrayList<Node>();
nodeList1.add(Bread0);
nodeList1.add(Bread1);
nodeList1.add(Bread2);
insert(root, parentId, nodeList1);
Add children for Milk
parentId = Milk.id;
Node Milk0 = new Node(21, "Whole");
Node Milk1 = new Node(22, "skim");
Node Milk2 = new Node(23, "Almond");
ArrayList<Node> nodeList2 = new ArrayList<Node>();
nodeList2.add(Milk0);
nodeList2.add(Milk1);
nodeList2.add(Milk2);
insert(root, parentId, nodeList2);
traverse(root);
}
}
class Node{
int id;
String data;
Node parent;
ArrayList<Node> children;
public Node(int id, String data)
{
this.id = id;
this.data = data;
}
}

Root is set null before very insert(int data) function call in testMain.java class like btree.insert(1); and btree.insert(2);

below is the code for BinaryTree.java insertion . Every time i insert a new node , the root is null.What i want , after 1st insert , root should not be null and it should remember the 1st insert and then for 2nd insert, the condition if (root ==null) should be false.
import java.util.LinkedList;
public class BinaryTree {
private BTNode root;
public int size;
public BinaryTree(){
this.root= null;
}
// public BTNode getRoot(){
// return this.root;
// }
public void insert(int data){
insert(data, root);
//calling insert function that takes data and root to insert
}
private void insert (int data, BTNode root){
//case 1: no element in binary tree
if (root == null){
// if root is null create a new BTNode and make it root
BTNode newN= new BTNode(data);
newN.setLeft(null);
newN.setRight(null);
root =newN;
//System.out.println(root.getData());
size++;
return;
//return root.getData();
}
//case2: tree not empty
//create a queue and traverse each node left-right
LinkedList<BTNode> q = new LinkedList<BTNode>();
q.addFirst(root);
while(!(q.isEmpty())){ //if queue not empty
BTNode temp= (BTNode) q.removeFirst();
//check left
if (temp.getLeft()==null){
//create a node and set left
BTNode newN= new BTNode(data);
newN.setLeft(null);
newN.setRight(null);
temp.setLeft(newN);
size++;
return;
//return root.getData();
}
else{
q.addLast(temp.getLeft());
}
//check right in case left is not null
if (temp.getRight()==null){
//create a node and set right
BTNode newN= new BTNode(data);
newN.setLeft(null);
newN.setRight(null);
temp.setRight(newN);
size++;
return;
//return root.getData();
}
else{
q.addLast(temp.getRight());
}
}//while loop ends here
return ;
}// insert(data,root) function ends here
}//class ends here
below is code for BTNode.java
public class BTNode {
int data;
private BTNode left=null;
private BTNode right=null;
public BTNode(){
}
public BTNode(int data){
this.data=data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public BTNode getLeft() {
return left;
}
public void setLeft(BTNode left) {
this.left = left;
}
public BTNode getRight() {
return right;
}
public void setRight(BTNode right) {
this.right = right;
}
}
TestMain.java
public class TestMain {
public static void main(String[] args){
BinaryTree btree = new BinaryTree();
btree.insert(1);
//System.out.println(btree.getRoot().getData());
btree.insert(2);
btree.insert(3);
btree.insert(4);
btree.insert(5);
btree.insert(6);
}
}
TestMain.Java
public class TestMain {
public static void main(String[] args){
BinaryTree btree = new BinaryTree();
btree.insert(1);
System.out.println(btree.getRoot().getData());
}
inside BinaryTree:
public BTNode getRoot(){
return this.root;
}
private void insert (int data, BTNode rootParameter){ // your problem is here
//case 1: no element in binary tree
if (root == null){
// if root is null create a new BTNode and make it root
BTNode newN= new BTNode(data);
newN.setLeft(null);
newN.setRight(null);
root =newN;
//System.out.println(root.getData());
size++;
return;
//return root.getData();
}
// other part of your code
}
the problem is that you are assigning your root to parameter but you should assign it to root variable outside of your method. you won't get null reference now.

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.

Categories