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
*/

boolean isLeafNode(TreeNode< E > node) {
return node.left == null && node.right == null;
}
/**
* Prints the tree in In-order. Basically, traverse the tree in the
* in-order. i.e. will traverse left,root and then right.
* @param node the node whose in-order to be find.
*/
public void printInorder(TreeNode< E > node) {
if (node == null) {
return;
}
printInorder(node.left);
System.out.print(node.value + " ");
printInorder(node.right);
}
/**
* Prints the Leaf node of the tree.
* @param node the node whose leaf node is to be find.
*/
public void printLeafNode(TreeNode< E > node) {
if (node != null && (node.left == null && node.right == null)) {
System.out.print(node.value + " ");
return;
}
if (node != null) {
printLeafNode(node.left);
printLeafNode(node.right);
}
}
/**
* Find the Height of the tree
* @param node find the height of the given node.
* @return the height of the tree.
*/
public int heightOfTree(TreeNode< E > node) {
if (node == null) {
return 0;
} else {
return 1 + Math.max(heightOfTree(node.left),
heightOfTree(node.right));
}
}
public String toString()
{
return "[ " + "root = "+value.toString() + " Left = "+
(left!=null ? left.value : null) + " Right = "+
(right!=null ? right.value:null) +" ]";
}
}

0 comments: