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;
}
}
Related
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 am writing a code to practice some linked list example with basics but came across a problem when in linked list class in voidadd method what does it means when I pass the Node variable that is "top" inside the node objects ? does it help it to point the previous data? i have indicated the part that refers to my question
public class Node
{
private int data;
private Node nextNode;
public Node(int dataP , Node nextNodeP)
{
data = dataP;nextNode = nextNodeP;
}
public int getData()
{
return data;
}
public Node getNextNode()
{
return nextNode;
}
public void setData(int newData) //to replace the value of some notes [12| ] --> [120| ]
{
data = newData;
}
public void setNext(Node newNextNode) // pointing to top ---> [120| ] ---> [last | null]
{
nextNode = newNextNode;
}
}
public class LinkedList {
private Node top;
private int size;
public LinkedList() {
top = null;
size = 0;
}
public int getSize() {
return size;
}
public void addNode(int newData) {
Node temp = new Node(newData, top); //question
top = temp; //points to the same
size++;
}
}
Define a node at its own class.
Here is a simple example :
public class LinkedList {
private Node first,last;
private int size ;
//adds node as last. not null safe
public void addNode(Node node) {
if(first == null) {
node.setParent(null);
first = node;
last = node;
}else {
node.setParent(last);
last = node;
}
size++;
}
public Node getFirst() {return first;}
public Node getLast() { return last; }
public int getSize() {return size;}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.addNode(new Node(0,null));
list.addNode(new Node(1,null));
list.addNode(new Node(2,null));
list.addNode(new Node(3,null));
Node node = list.getLast();
System.out.println("list has "+ list.size + " nodes:");
while(node != null) {
System.out.println(node);
node = node.getParent();
}
}
}
class Node{
private int data;
private Node parent;
Node(int nodeData, Node parent) {
data = nodeData;
this.parent = parent;
}
public int getData() { return data;}
public void setData(int data) { this.data = data; }
public Node getParent() {return parent; }
public void setParent(Node parent) {this.parent = parent;}
#Override
public String toString() {return "Node "+getData() +" parent:"+ getParent();}
}
I wrote this code to create a binary tree but looks like this code is creating an unbalanced binary tree. The nodes are getting only on the right subtree of root. I get Null pointer exception if I try to access child nodes of left subtree. I want to create a balanced binary tree with nodes getting inserted from left to right. What mistake am I doing here and how to rectify it?
public class binTree {
public static class TreeNode{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val){
this.val = val;
this.left = null;
this.right = null;
}
}
public TreeNode root;
public binTree(){
this.root = null;
}
public void insert(int data){
root = insert(root,data);
}
public TreeNode insert(TreeNode node,int data){
if(node == null){
node = new TreeNode(data);
//root = node;
}
else{
if(node.left == null){
node.left = insert(node.left,data);
}
else{
node.right = insert(node.right,data);
}
}
return node;
}
public static void main(String args[]){
binTree obj = new binTree();
obj.insert(5);
obj.insert(11);
obj.insert(13);
obj.insert(1);
obj.insert(7);
obj.insert(21);
obj.insert(35);
System.out.println(obj.root.right.left.val);
System.out.println(obj.root.left.right.val); // this throws null pointer exception
}
}
You'll need to store the quantity of elements for every sub-tree at each tree-node like this:
public class BinTree {
private TreeNode root;
public static class TreeNode {
public int val;
public int elements = 0;
public TreeNode left;
public TreeNode right;
public TreeNode(int val) {
this.val = val;
this.left = null;
this.right = null;
}
}
public BinTree() {
this.root = null;
}
public void insert(int data) {
root = insert(root, data);
}
private static int height(TreeNode node) {
int result = 0;
if (node != null) {
result++;
int total = node.elements;
int heightElements = 2;
while (total > heightElements) {
total -= heightElements;
heightElements *= 2;
result++;
}
}
return result;
}
public TreeNode insert(TreeNode node, int data) {
if (node == null) {
node = new TreeNode(data);
} else if (height(node.left) == height(node.right)) {
node.left = insert(node.left, data);
} else {
node.right = insert(node.right, data);
}
node.elements++;
return node;
}
public static void main(String args[]) {
BinTree obj = new BinTree();
obj.insert(5);
obj.insert(11);
obj.insert(13);
obj.insert(1);
obj.insert(7);
obj.insert(21);
obj.insert(35);
System.out.println(obj.root.val);
System.out.println(obj.root.left.val);
System.out.println(obj.root.right.val);
System.out.println(obj.root.left.left.val);
System.out.println(obj.root.left.right.val);
System.out.println(obj.root.right.left.val);
System.out.println(obj.root.right.right.val);
}
}
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.