I have implemented a Binary search tree with insert and traversal method but am not getting correct output for PreOrder and Postorder ,am getting inOrder in correct order. Could some one please tell me where am wrong.
I tried the same example on paper but the PreOrder and PostOrder is not same.
Here is my Code
Node Class
package com.BSTTest;
public class Node implements Comparable<Node> {
private int data;
private Node leftChild;
private Node rightChild;
public Node(int data) {
this(data, null, null);
}
public Node(int data, Node leftChild, Node rightChild) {
this.data = data;
this.leftChild = leftChild;
this.rightChild = rightChild;
}
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;
}
public int compareTo(Node o) {
return Integer.compare(this.data, o.getData());
}
}
Tree Class
package com.BSTTest;
import com.BSTTest.Node;
public class Tree {
private Node root = null;
public Node getRoot() {
return root;
}
//Inserting data**strong text**
public void insertData(int data) {
Node node = new Node(data, null, null);
if (root == null) {
root = node;
} else {
insert(node, root);
}
}
//Helper method for insert
private void insert(Node node, Node currNode) {
if (node.compareTo(currNode) < 0) {
if (currNode.getLeftChild() == null) {
currNode.setLeftChild(node);
} else {
insert(node, currNode.getLeftChild());
}
} else {
if (currNode.getRightChild() == null) {
currNode.setRightChild(node);
} else {
insert(node, currNode.getRightChild());
}
}
}
public void printInorder() {
printInOrderRec(root);
System.out.println("");
}
//Helper method to recursively print the contents in an inorder way
private void printInOrderRec(Node currRoot) {
if (currRoot == null) {
return;
}
printInOrderRec(currRoot.getLeftChild());
System.out.print(currRoot.getData() + ", ");
printInOrderRec(currRoot.getRightChild());
}
public void printPreorder() {
printPreOrderRec(root);
System.out.println("");
}
// Helper method for PreOrder Traversal recursively
private void printPreOrderRec(Node currRoot) {
if (currRoot == null) {
return;
}
System.out.print(currRoot.getData() + ", ");
printPreOrderRec(currRoot.getLeftChild());
printPreOrderRec(currRoot.getRightChild());
}
public void printPostorder() {
printPostOrderRec(root);
System.out.println("");
}
/**
* Helper method for PostOrder method to recursively print the content
*/
private void printPostOrderRec(Node currRoot) {
if (currRoot == null) {
return;
}
printPostOrderRec(currRoot.getLeftChild());
printPostOrderRec(currRoot.getRightChild());
System.out.print(currRoot.getData() + ", ");
}
//Main Mthod
public static void main(String[] args) {
Tree obj = new Tree();
//Inserting data
obj.insertData(3);
obj.insertData(5);
obj.insertData(6);
obj.insertData(2);
obj.insertData(4);
obj.insertData(1);
obj.insertData(0);
//printing content in Inorder way
System.out.println("Inorder traversal");
obj.printInorder();
//printing content in Inorder way
System.out.println("Preorder Traversal");
obj.printPreorder();
//printing content in Inorder way
System.out.println("Postorder Traversal");
obj.printPostorder();
}
}
Look my friend,your code is absolutely fine as the outputs you mentioned are absolutely correct.
I think you have not understood the concept of Binary Search Tree correctly.
You are right,3 is root node but you wrong in saying that 1 is its left child.
The first value that appears after 3 and that is smaller than 3 is 2,therefore 2 is left child of 3 and not 1
Refer to Cormenn book if still there is confusion.
Related
I have to make a source code about binary tree from anything type. That means the input is string, so in my opinion, I must convert the string into byte[ ] then get the ASCII code from that. But I don't know how to make binary tree from byte or convert that byte[ ] into integer. I'm stuck right now.
class Node{
int data;
Node left, right;
public Node(int data){
this.data = data;
Node left = right = null;
}
}
class BinaryTree{
public Node root;
public void newNode(int data){
if(root == null){
root = newNode(root, new Node(data));
}
}
private Node newNode(Node root, Node newData){
if(root == null){
root = newData;
return root;
}
if(newData.data < root.data){
root.left = newNode (root.left, newData);
}else{
root.right = newNode (root.right, newData);
}
return root;
}
public void inOrder(Node node){
if(node !=null){
inOrder(node.left);
System.out.println(node.data + " ");
inOrder(node.right);
}else{
return;
}
}
public void preOrder(Node node){
if(node !=null){
System.out.println(node.data +" ");
preOrder(node.left);
preOrder(node.right);
}else{
return;
}
}
public void postOrder(Node node){
if(node !=null){
preOrder(node.left);
preOrder(node.right);
System.out.println(node.data +" ");
}else{
return;
}
}
}
public class ALPROMOD5{
public static void main(String[] args) throws UnsupportedEncodingException {
Scanner scan = new Scanner(System.in);
String inp;
System.out.println("String to ASCII");
System.out.println("Binary Tree from Converted String to Char");
System.out.print("\nMasukan Inputan : ");
inp = scan.nextLine();
byte[] bt = inp.getBytes("US-ASCII");
System.out.print("ASCII Value of("+inp+") is : ");
System.out.println(Arrays.toString(bt));
}
}
Look at generics. No need to convert your data at all. Here's a place to start:
NOTE: For comparisons, use the compareTo() method from the comparable interface.
public class Node<T extends Comparable<T>> {
private T payload;
private Node<T> leftNode;
private Node<T> rightNode;
public Node(T payload) {
this.payload = payload;
}
public T getPayload() {
return payload;
}
public Node<T> getLeftNode() {
return leftNode;
}
public Node<T> getrightNode() {
return rightNode;
}
public void setLeftNode(Node<T> left) {
leftNode = left;
}
public void setRightNode(Node<T> right) {
rightNode = right;
}
}
public class BinaryTree<T extends Comparable<T>> {
private Node<T> root;
public BinaryTree(T rootPayload) {
root = new Node<T>(rootPayload);
}
public Node<T> addNode(T data) {
return add(root, data);
}
private Node<T> add(Node<T> root, T data) {
//Add your code returning the node representing the data.
return null;
}
}
I'm learning the BST implementation, this is my code for insertion and inorder function. I have a doubt regarding the inorder function
public class BSTtry {
Node root;
class Node{
int data;
Node left,right;
Node(int data){
this.data=data;
left=right=null;
}
}
public void insert(int data) {
root=insertdata(root,data);
}
public void inorder(){
printinorder(root);
}
public Node insertdata(Node root,int data) {
if(root==null) {
root=new Node(data);
return root;
}
if(data<root.data) {
root.left=insertdata(root.left,data);
}
if(data>root.data) {
root.right=insertdata(root.right,data);
}
return root;
}
public void printinorder(Node root) {
if(root!=null) {
printinorder(root.left);
System.out.print(root.data+" ");
printinorder(root.right);
}
}
public static void main(String[] args) {
BSTtry bst=new BSTtry();
//Inserted some values in the tree
bst.printinorder(root);
}
}
So when I try to use the bst.printinorder(root); an error is thrown Cannot make a static reference to the non-static field root.
So can I change the root to static or print the inorder by calling the inorder() function.Which is a better way??
Main methods are static, root is a field of BSTtry.
Yes you could change the field to static but that's not what you want.
You should initialize the field e.g with a setter or with an constructor, having a Node argument.
Best regards
Just use inorder() instead, which calls printinorder() with root as the first argument.
bst.inorder();
Remove Node class out of BSTtry Class,
it will work
class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
left = right = null;
}
}
public class BSTtry {
Node root;
public void insert(int data) {
root = insertdata(root, data);
}
public void inorder() {
printinorder(root);
}
public Node insertdata(Node root, int data) {
if (root == null) {
root = new Node(data);
return root;
}
if (data < root.data) {
root.left = insertdata(root.left, data);
}
if (data > root.data) {
root.right = insertdata(root.right, data);
}
return root;
}
public void printinorder(Node root) {
if (root != null) {
printinorder(root.left);
System.out.print(root.data + " ");
printinorder(root.right);
}
}
public static void main(String[] args) {
BSTtry bst=new BSTtry();
//Inserted some values in the tree
Node a = new Node(1);
a.left = new Node(2);
bst.printinorder(a);
}
}
I am trying this code to populate the BST and then print it in the InOrder traversal format. But the root node is not getting populated compiling wihtout any error and Output is : "root is empty", so how to correct this code so that my BST gets populated in the Node root.
I tried to make Node root as static I thought it might be the case that root node might not be accessible from each method but it is not working, tried to change the name of the Node but it is also not working.
import java.util.*;
import java.io.*;
import java.lang.*;
class Node{
int data; Node left; Node right;
public Node(int data) {
this.data = data;
left = null;
right = null;
}
}
public class insert_tree {
static Node root;
insert_tree() //constructor
{
root = null;
}
public void addNode(int value) { // public method is called by the object and this public method calls the private method in which the root is also passed.
root = add(root, value);
}
private Node add(Node node, int value) {
if(node == null) {
return node;
}
if(value < node.data) {
node.left = add(node.left, value);
}
else if(value > node.data) {
node.right = add(node.right, value);
}
else {
return node;
}
return node;
}
private void inOrder(Node node) {
// node = root;
if(node != null) {
inOrder(node.left);
System.out.print(node.data + " ");
inOrder(node.right);
}
else {
System.out.print("root is empty");
}
//return null;
}
public void inorder() {
inOrder(root);
}
private void printRoot(Node root) {
System.out.println(root.data);
}
public void print() {
printRoot(root);
}
public static void main(String args[]) {
insert_tree obj = new insert_tree();
obj.addNode(20);
obj.addNode(14);
obj.addNode(25);
obj.addNode(10);
obj.addNode(16);
obj.addNode(25);
obj.addNode(21);
obj.addNode(30);
//printing the tree
obj.inorder();
}
}
The output should be the inorder traversal of the tree.
public void addNode(int value) { // public method is called by the object and this public method calls the private method in which the root is also passed.
root = add(root, value);
}
private Node add(Node node, int value) {
if(node == null) {
node = new Node(value);
}
else if(value == node.data) {
node.data = value;
}
else if(value < node.data) {
node.left = add(node.left, value);
}
else {
node.right = add(node.right, value);
}
return node;
}
I'm trying to create binary tree by following example 1 where tree is made without getters and setters. I would like to create it with geeters and setters but I'm stuck on line with recursion. How can I call recursion function with/inside setter? Here is the code..
p.s. Tree class pastebin
public class TreeF {
Tree root;
public void insert(int value) {
if (root==null) {
root = new Tree(value);
return;
}
Tree current = root;
if (value < current.getData() ) {
if (current.getLeft()==null) {
current.setLeft(new Tree (value));
}else {
// call insert method inside current.left object [currrent.left(insert(value))]
current=current.getLeft();
insert (value);
}
}
else {
if (current.getRight()==null) {
current.setRight(new Tree (value));
}else {
current=current.getRight();
insert (value);
}
}
}
}
Change insert(value) to current.insert(value)
To implement recursion, you need to change a parameter(or multiple) so you can go to the stopping condition after some recursive calls.
In your code, you called the method insert that was part of the same object. And not its left/right subtree. In other words, the recursion never ends, because you don't visit the child subtrees.
public class Tree {
private int data;
private Tree left;
private Tree right;
public Tree (int data) {
this.data=data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Tree getLeft() {
return left;
}
public void setLeft(Tree left) {
this.left = left;
}
public Tree getRight() {
return right;
}
public void setRight(Tree right) {
this.right = right;
}
public void insert(int value) {
if (value < getData()) {
if (getLeft() == null) {
setLeft(new Tree(value));
} else {
getLeft().insert(value);
}
} else {
if (getRight() == null) {
setRight(new Tree(value));
} else {
getLeft().insert(value);
}
}
}
}
You do not need a current field or a root. Here's your insert method greatly simplified to demonstrate.
public class Tree {
final int data;
Tree left;
Tree right;
public Tree(int value) {
data = value;
}
public void insert(int value) {
if (value < data) {
if (left == null) {
left = new Tree(value);
} else {
left.insert(value);
}
} else {
if (right == null) {
right = new Tree(value);
} else {
right.insert(value);
}
}
}
}
I'm trying to make a tree structure based on the linked list. Since linked list can only directly point to the next node(For singly linked list), I would like to modify the concept of the linked list. Is it possible to point at the one node from multiple nodes?
Here is an image in drawing
I think the following would work:
class Node {
Node sibling;
Node child;
Object item;
}
sibling will point to next Node at parallel level, child points to Node on lower level.
See below my implementation:
package treeTest;
public class Node {
private Node left;
private Node right;
private String data;
public Node(String data) {
this.data = data;
left = null;
right = null;
}
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;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
package treeTest;
public class Tree {
private Node root;
public Tree() {
root = null;
}
public void insert(String data) {
root = insert(root, data);
}
private Node insert(Node node, String data) {
if(node == null) {
// Then create tree
node = new Node(data);
} else {
if(data.compareTo(node.getData()) <= 0) {
node.setLeft( insert(node.getLeft(), data));
} else {
node.setRight(insert(node.getRight(), data));
}
}
return node;
}
}
package treeTest;
import java.util.Scanner;
public class TestTree {
public static void main(String[] args) {
// TODO Auto-generated method stub
Tree tree = new Tree();
tree.insert("Hurricane");
// Second level
tree.insert("Cat1");
tree.insert("Cat2");
tree.insert("Cat3");
}
}
For more details checkout this Java Program to Implement a Binary Search Tree using Linked Lists