java program printing weird hexadecimal output - java

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());

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.

Initiating a binary search tree using a rootNode that is null

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) {}
}

Printing linked list in java

I couldn't print the linked list it infinitely prints 4 as the value. What is wrong with this code ? In the below code, I am trying to implement a singly linked list after adding every element while am trying to print it infinitely prints 4 as output any idea why?
import java.util.*;
class Linkedit{
static class Node{
static Node next;
int data;
Node(int t){
data=t;
next=null;
}
}
Node head=null;
public void insert(int data){
Node k=new Node(data);
k.next=head;
head=k;
}
public void show(){
Node a=head;
while(a!=null){
System.out.println(a.data);
a=a.next;
}
}
public static void main(String args[]){
Linkedit g=new Linkedit();
g.insert(3);
g.insert(4);
g.insert(5);
g.show();
}
}
Here's the problem:
static Node next;
The next member should not be static, since each Node should have a different next value.
Changing
static class Node {
static Node next;
int data;
Node(int t){
data=t;
next=null;
}
}
to
static class Node {
Node next;
int data;
Node(int t){
data=t;
next=null;
}
}
Solves your problem.

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.

Inserting a node in BST

I am trying to insert nodes in my custom BST.The first time the insertData method is called , the new node is correctly inserted as the root.The problem is occuring in the second and subsequent calls.
Below is My code :
1.The Node Class =
package ishan.trees.tree;
class Node implements Comparable<Node> {
private int data;
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getLeftChild() {
return leftChild;
}
public void setLeftChild(Node leftChild) {
this.leftChild = leftChild;
}
public Node getRightChild() {
return rightChild;
}
public void setRightChild(Node rightChild) {
this.rightChild = rightChild;
}
private Node leftChild;
private Node rightChild;
public Node(int data,Node leftChild,Node rightChild)
{
this.data=data;
this.leftChild=leftChild;
this.rightChild=rightChild;
}
#Override
public int compareTo(Node o) {
if(o.getData() > this.data)
return -1;
if(o.getData() < this.data)
return 1;
return 0;
}
}
The Tree Class =
package ishan.trees.tree;
public class Tree {
private Node root=null;
public Node getRoot() {
return root;
}
public void insertData(int data)
{
Node node=new Node(data,null,null);
insert(node,this.root);
}
private Node insert(Comparable<Node> node,Node root1)
{
if(root1==null)
{//insert as first element ie root
this.root=new Node(((Node)node).getData(),null,null);
}
else if(node.compareTo(root1) <0)
{
root1.setLeftChild(insert(node,root1.getLeftChild()));
}
else if(node.compareTo(root1) >0)
{
root1.setLeftChild(insert(node,root1.getRightChild()));
}
return root1;
}
}
3.Main Class =
package ishan.trees.usage;
import ishan.trees.tree.Tree;
public class Usuage {
public static void main(String a[])
{
Tree tree=new Tree();
tree.insertData(10); //---------1
tree.insertData(15); //---------2
tree.insertData(9); //---------3
tree.insertData(4); //---------4
}
}
when i debug the second call it is something like this:
insertData(15){
insert(15,10)
}
which makes a call to the insert method as ---->
insert(15,null)
I get this null every time and this results in the current node replacing the root node.
I cant figure out why during the call , the root1 reference is null and not pointing to my root?
More Info :
Its during the call from insertData() to insert() . say During my second call to insertData(15) , i make a call to insert(15,this.root) -->insert(node,root1) . but this root1 reference turns out to be null.but when i inspect this.root it is referring to the correct root node..
Thanks!
Alright here is dry run for your code,
Inserting 10.
When you insert first element, this API insert creates a new root for you as per your code and sets it value to 10,
now second insertion makes it interesting, watch what happenes
StackTrace
insertData(15);
insert(node,root) // here root is your actuall root, originally initialized when u inserted first
// it goes to last else if inside insert api
root1.setRightChild(insert(node,root1.getRightChild())); // see now, this apis actually calls insert again, coz new node value was greater then root value
// this is how next stack trace will look like, as root right child was null
insert(node,null); // observer second argument is null again
now as per your Insert code will end up creating root again(root1 argument is null, first condition is executed), discarding previously defined root. this is what is causing your issue you are overriding your root again and again.
After inserting first node i.e root, left and right node will be null. Next time while inserting left or right child node you are not checking that condition.
private Node insert(Comparable<Node> node,Node root1)
{
if(root1==null)
{//insert as first element ie root
this.root=new Node(((Node)node).getData(),null,null);
}
else if(node.compareTo(root1) <0)
{
if(root1.getLeftChild()==null)
root1.setLeftChild(node);
else
root1.setLeftChild(insert(node,root1.getLeftChild()));
}
else if(node.compareTo(root1) >0)
{
if(root1.getRightChild()==null)
root1.setRightChild(node);
else
root1.setRightChild(insert(node,root1.getRightChild()));
}
return root1;
}

Categories