Binary Tree

Binary tree implementation in java

<<<<<<<<<<<<<<<<<BinaryTreeNode.java>>>>>>>>>>>>>>>>>>>>>>>

public class BinaryTreeNode
{
private int key;
private BinaryTreeNode leftLink;
private BinaryTreeNode rightLink;

public void setKey(int key)
{
this.key = key;
}

public int getKey()
{
return this.key;
}

public void setLeftLink(BinaryTreeNode bNode)
{
this.leftLink = bNode;
}

public void setRightLink(BinaryTreeNode bNode)
{
this.rightLink = bNode;
}

public BinaryTreeNode getLeftLink()
{
return this.leftLink;
}

public BinaryTreeNode getRightLink()
{
return this.rightLink;
}

public static BinaryTreeNode createNode(int key, BinaryTreeNode leftLink, BinaryTreeNode rightLink)
{
BinaryTreeNode bNode = new BinaryTreeNode();
bNode.setKey(key);
bNode.setLeftLink(leftLink);
bNode.setRightLink(rightLink);
return bNode;
}
}

 

<<<<<<<<<<<<<<<<<<<<<<<BinaryTree.java>>>>>>>>>>>>>>>>>>>>>>>>

public class BinaryTree
{
static BinaryTreeNode rootNode;
BinaryTreeNode parentNode=null;

public BinaryTree()
{
rootNode = null;
}

public void addNode(int key , BinaryTreeNode leftLink, BinaryTreeNode rightLink)
{
if(rootNode!=null)
{
BinaryTreeNode bNode = rootNode;
BinaryTreeNode parentNode;
while(true)
{
if(bNode.getKey()>key)
{
parentNode = bNode;
bNode = bNode.getLeftLink();
if(bNode==null)
{
BinaryTreeNode bChildNode = BinaryTreeNode.createNode(key, null, null);
parentNode.setLeftLink(bChildNode);
System.out.print("child with key ("+key+") added successfully in the left subtree with parent ("+parentNode.getKey()+")\n");
return;
}
}
else if(bNode.getKey()key)
{
parentNode = bNode;
bNode = bNode.getLeftLink();
if(bNode==null)
{
System.out.print("Key ("+key+") not found!!\n");
return;
}
}
else if(bNode.getKey()

Rate this post

Leave a Reply