Spiga

Basic TreeNode Structure in Java using Generics

Basic TreeNode Structure Using Generics

This is the basic block for creating the binary tree. We generally call this block or the structure as a Node. So this is how a single node is created. This in itself is a tree and when we pile the number of nodes, it become a big tree.

Here is the code, to create the TreeNode.

/**
* Basic Structure of the Tree. Or the Single unit of a tree.
* @author Sonu Mishra
* @param Type of the Node for the tree. Like. String, Integer
*/
TreeNode< E extends Comparable<? super E>>
{
public TreeNode< E > left;
public TreeNode< E > right;
E value;
public TreeNode(TreeNode< E > left, TreeNode< E > right, E value) {
this.left = left;
this.right = right;
this.value = value;
}
/**
* If a node doesn't have left and right child, it is leaf node.
* @param node check whether this node is leaf node or not.
* @return either true or false
*/

JAVA WAY TO WRITE TREE

JAVA WAY TO WRITE BINARY SEARCH TREE

A binary search tree (BST),is a node-based data structure in which each node has no more than two child nodes. Each child must either be a leaf node or the root of another binary search tree. The left sub-tree contains only nodes with keys less than the parent node; the right sub-tree contains only nodes with keys greater than the parent node.BST is also known as an ordered binary tree.
BST
Here is the Code to create a binary search tree in java.

import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.Stack;
/**
* Creates a Binary Search Tree.
* @author Sonu Mishra
*/
public class BinarySearchTree<E extends Comparable<? super E>>
{
private TreeNode<E> root = null;
public BinarySearchTree() {
root = new TreeNode(null, null, null);
}
public BinarySearchTree(E value) {
root = new TreeNode(null, null, value);
}
public void add(E value) {
addBefore(value, this.root);
}