April 28, 2020

Create a simple Tree data structure in Java from an array of values

Tree is a data Structure to create a hierarchical structure


Creating a Node class



/**
 * Node in Tree
 */
package com.cfed.datastructures;

/**
 * @author Konzernites
 *
 */
public class Node {

private int data;
private Node left;
private Node right;

public Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}

public String toString() {
return "data is "+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;
}
}


Adding  values to a tree



/**
 * Adding values to tree
 */
package com.cfed.datastructures;

/**
 * @author Konzernites
 *
 */
public class BinaryTree {

private Node root;

private Node addRecursion(Node current, int data) {
if (null == current) {
return new Node(data);
} else if( null == current.getLeft()) {
current.setLeft(addRecursion(current.getLeft(), data));
}else if(null == current.getRight()) {
current.setRight(addRecursion(current.getRight(), data));
}else {
addRecursion(current.getLeft(), data);
}
return current;
}

public void addData(int value) {
root = addRecursion(root, value);
}
}


Mainclass.java the entry class


/**
 *  Entry point of the program
 */
package com.cfed.datastructures;

/**
 * @author Athul Ramesh
 *
 */
public class TreeTesting {

public static void main(String[] args) {
int arr[] = {8,6,7,4,3,1,2};
BinaryTree binary = new BinaryTree();
for(int i =0; i< arr.length; i++) {
binary.addData(arr[i]);
}
}
}


You can use this program to store data in a hierarchical structure.

No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments