You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Binary search tree (BST) is a binary tree data structure, in which the values in the left sub-trees of every node are smaller and the values in the right sub-trees of every node are larger.
0. --| Class defination containing all above Functions().
classBST{
classNode{
intdata;
Nodeleft;
Noderight;
publicNode(intval) {
data=val;
left=right=null;
}
}
Noderoot;
publicBST() {
root=null;
}
publicbooleanisTreeEmpty() {
returnroot==null;
}
// and above functions like insertion, deletion, printing, traversing and manymore.... all function defination will come below as you understand each functions operations./* . . . . */
}
1. --| Insertion in BST(itterative approach).
// Main function callingBSTbt=newBST(); //BST is a class containing all the above functionscase1:
System.out.println("Enter value");
val=sc.nextInt();
bt.insertNodeITTE(val);
break;
//1.--| Insertion in BST(itterative approach) STARTSpublicvoidinsertNodeITTE(intval) {
Noden=newNode(val);
if(isTreeEmpty())
{
root=n;
System.out.println("Value inserted as root node");
}
else {
Nodetemp=root;
while(temp!=null) {
if(val==temp.data) {
System.out.println("Value already exist");
return;
}
//for left insertion i.e., when val<currNodeelseif(val<temp.data && temp.left==null) {
temp.left=n;
System.out.println("Value inserted to left");
break;
}
elseif(val<temp.data) {
temp=temp.left;
}
//for right insertion i.e., when val>currNodeelseif(val>temp.data && temp.right==null) {
temp.right=n;
System.out.println("Value inserted to right");
break;
}
else//(val>temp.data)
{
temp=temp.right;
}
}
}
}
//1.--| Insertion in BST(itterative approach) ENDS
2. --| Insertion in BST(recurrsive approach).
// Main function callingBSTbt=newBST(); //BST is a class containing all the above functionscase2:
System.out.println("Enter value");
val=sc.nextInt();
bt.root=bt.insertNodeRECURR(bt.root, val);
break;
//2.--| Insertion in BST(recurrsive approach) STARTSpublicNodeinsertNodeRECURR(Noderoot, intkey) {
// if the root is null, create a new node and return itif (root == null)
returnnewNode(key);
// if the given key is less than the root node,// recur for the left subtreeelseif (key < root.data)
root.left = insertNodeRECURR(root.left, key);
// otherwise, recur for the right subtreeelseif(key > root.data)
root.right = insertNodeRECURR(root.right, key);
else// key== root.dataSystem.out.println("Dublicate value not allowed");
returnroot;
}
//2.--| Insertion in BST(recurrsive approach) ENDS
3. --| Insertion in BT(level order insertion).
// Main function callingBSTbt=newBST(); //BST is a class containing all the above functionscase3:
System.out.println("Enter value");
val=sc.nextInt();
bt.insert(bt.root, val);
break;
//3.--| Insertion in BT(level order insertion) STARTSpublicvoidinsert(Nodert,intval) {
Nodenn=newNode(val);
if(rt==null) {
rt=nn;
System.out.println("inserted at root");
root=rt;
return;
}
Queue<Node> q=newLinkedList<Node>();
q.add(rt);
while(!q.isEmpty()) {
Noden=q.element();
q.remove();
if(n.left==null) {
n.left=nn;
System.out.println("inserted left of BT");
root=rt;
return;
}
elseif(n.right==null) {
n.right=nn;
System.out.println("inserted right of BT");
root=rt;
return;
}
else {
q.add(n.left);
q.add(n.right);
}
}
}
//3.--| Insertion in BT(level order insertion) ENDS
// Main function callingBSTbt=newBST(); //BST is a class containing all the above functionscase4:
bt.print2D(bt.root, 5);
break;
//4.--| Print 2D STARTSpublicvoidprint2D(Noder,intspace) {
if (r ==null) // Base case 1return;
print2D(r.right,space+5);
System.out.println();
for(inti=0;i<space;i++)
System.out.print(" ");
System.out.println(r.data);
print2D(r.left,space+5);
}
//4.--| Print 2D ENDS
// Main function callingBSTbt=newBST(); //BST is a class containing all the above functionscase5: System.out.println(bt.Height(bt.root));
break;
case6: System.out.println(bt.sumOfBT(bt.root));
break;
case7:System.out.println(bt.countNodes(bt.root));
break;
case8: System.out.println(bt.maxNoBT(bt.root));
break;
//5.--| Height of tree / 18.-| isBalanced() STARTSstaticbooleanisBal=true;//only to find balanced BT, ignore.publicstaticintHeight(Noder) {
if(r==null) return -1;
else {
intlh=Height(r.left);
intrh=Height(r.right);
// ignore THIS, while thinking about height of BTif(Math.abs(lh-rh)>1)
isBal=false;
// }returnMath.max(lh, rh)+1;
}
}
//5.--| Height of tree / 18.-| isBalanced() ENDS//6.--| Sum of BT STARTSpublicintsumOfBT(Noder) {
if(r==null) {
return0;
}
intlsum=sumOfBT(r.left);
intrsum=sumOfBT(r.right);
returnlsum+rsum+r.data;
}
//6.--| Sum of BT ENDS//7.--| No. of nodes in BT STARTSpublicintcountNodes(Noder) {
if(r==null) {
return0;
}
intlc=countNodes(r.left);
intrc=countNodes(r.right);
returnlc+rc+1;
}
//7.--| No. of nodes in BT ENDS//8.--| Maximum value in BT STARTSpublicintmaxNoBT(Noder) {
if(r==null) returnInteger.MIN_VALUE;
intlmax=maxNoBT(r.left);
intrmax=maxNoBT(r.right);
returnMath.max(r.data, Math.max(lmax, rmax));
}
//8.--| Maximum value in BT ENDS
// Main function callingBSTbt=newBST(); //BST is a class containing all the above functionscase14: bt.rootToleaf(bt.root);
break;
//14.-| All paths from root to leaf nodes STARTS//print path from root to leafnodes just modifying Inorder and using stacks.staticStack<Integer> st=newStack();
publicstaticvoidroot2leaf(Noderoot){
if(root == null) return;
st.push(root.val);
root2leaf(root.left);
root2leaf(root.right);
if(root.left==null && root.right==null)
System.out.println(st);
st.pop();
}
//14.-| All paths from root to leaf nodes ENDS
// Main function callingBSTbt=newBST(); //BST is a class containing all the above functionscase15:System.out.println("Enter value to search");
val=sc.nextInt();
System.out.println(bt.Search(val));
break;
//15.-| Search in BST STARTSpublicbooleanSearch(intval) {
booleanflag=false;
if(root==null)
{
System.out.println("Binary Tree is empty");
}
else {
Nodetemp=root;
while(temp!=null) {
if(val==temp.data) { flag= true; break;}
elseif(val<temp.data) temp=temp.left;
elseif(val>temp.data) temp=temp.right;
}
}
returnflag;
}
//15.-| Search in BST ENDS
16. -| Diameter of BT(nibbi approach).
17. -| Diameter of BT(legend approach).
// Main function callingimporttreeDS.BST.DiaPair;
BSTbt=newBST(); //BST is a class containing all the above functionscase16: System.out.println(bt.diameterOfBT(bt.root));
break;
case17: DiaPaird=newDiaPair();
d=bt.diameter(bt.root);
System.out.println(d.dia);
break;
//16.-| Diameter of BT(nibbi approach) STARTSpublicstaticintdiameterOfBT(Noder) {
if(r==null) return0;
//maximum distance between two nodes of LHS (factor 1)intld=diameterOfBT(r.left);
//maximum distance between two nodes of RHS (factor 2)intrd=diameterOfBT(r.right);
//maximum distance between left's deepest & right's deepest nodes (factor 3)intdes=Height(r.left)+Height(r.right)+2;
intdia =Math.max(des, Math.max(ld, rd));
returndia;
}
//16.-| Diameter of BT(nibbi approach) ENDS//17.-| Diameter of BT(legend approach) STARTSstaticclassDiaPair{
intht;
intdia;
}
publicstaticDiaPairdiameter(Nodenode) {
if(node==null) {
DiaPairbp=newDiaPair();
bp.ht=-1;
bp.dia=0;
returnbp;
}
DiaPairlp=diameter(node.left);
DiaPairrp=diameter(node.right);
DiaPairmp=newDiaPair();
mp.ht=Math.max(lp.ht, rp.ht)+1;
intdes=lp.ht + rp.ht + 2;
mp.dia=Math.max(des, Math.max(lp.dia, rp.dia));
returnmp;
}
//17.-| Diameter of BT(legend approach) ENDS
// Main function callingBSTbt=newBST(); //BST is a class containing all the above functionscase20:
System.out.println("No. of Nodes in your BT ?");
val=sc.nextInt();
intpreorder[]=newint[val];
intinorder[]=newint[val];
System.out.println("Enter values in preorder sequence");
for(inti=0;i<val;i++)
preorder[i]=sc.nextInt();
System.out.println("Enter values in inorder sequence");
for(inti=0;i<val;i++)
inorder[i]=sc.nextInt();
bt.root=bt.buildTreeFromInorderPreorder(preorder,inorder);
break;
//20.-| Construct BT from Preorder and Inorder STARTSpublicNodebuildTreeFromInorderPreorder(intpreorder[],intinorder[]){
intn=preorder.length;
System.out.println("Your BT is ready PRESS 4 AND ENTER to view");
returnpreInTree(preorder,0,n-1,inorder,0,n-1);
}
//psi=preorder starting index, pei=preorder ending index.//isi=inorder starting index, iei=inorder ending inex.publicNodepreInTree(intpre[],intpsi,intpei,intin[],intisi,intiei) {
if(isi>iei) returnnull;
intpreVal=pre[psi];
Noden=newNode(preVal);
intidx=isi;
while(in[idx]!=pre[psi])
idx++;
inttnel=idx-isi;// total no. of element on left side/right side of root.n.left=preInTree(pre, psi+1, psi+tnel, in, isi,idx-1);
n.right=preInTree(pre, psi+tnel+1, pei, in, idx+1, iei);
returnn;
}
//20.-| Construct BT from Preorder and Inorder ENDS
// Main function callingBSTbt=newBST(); //BST is a class containing all the above functionscase21:
System.out.println("No. of Nodes in your BT ?");
val=sc.nextInt();
intpostorder[]=newint[val];
inorder=newint[val];
System.out.println("Enter values in postorder sequence");
for(inti=0;i<val;i++)
postorder[i]=sc.nextInt();
System.out.println("Enter values in inorder sequence");
for(inti=0;i<val;i++)
inorder[i]=sc.nextInt();
bt.root=bt.buildTreeFromInorderPostorder(postorder,inorder);
break;
//21.-| Construct BT from Postorder and Inorder STARTSpublicNodebuildTreeFromInorderPostorder(intpostorder[],intinorder[]){
intn=postorder.length;
System.out.println("Your BT is ready PRESS 4 AND ENTER to view");
returnpostInTree(postorder,0,n-1,inorder,0,n-1);
}
//psi=postorder starting index, pei=postorder ending index.//isi=inorder starting index, iei=inorder ending inex.publicNodepostInTree(intpost[],intpsi,intpei,intin[],intisi,intiei) {
if(isi>iei) returnnull;
Noden=newNode(post[pei]);
intidx=isi;
while(in[idx]!=post[pei])
idx++;
inttnel=idx-isi;// total no. of element on left side/right side of root.n.left=postInTree(post, psi, psi+tnel-1, in, isi,idx-1);
n.right=postInTree(post, psi+tnel, pei-1, in, idx+1, iei);
returnn;
}
//21.-| Construct BT from Postorder and Inorder ENDS
// Main function callingBSTbt=newBST(); //BST is a class containing all the above functionscase22:
System.out.println("No. of Nodes in your BT ?");
val=sc.nextInt();
inorder=newint[val];
System.out.println("Enter values in inorder sequence");
for(inti=0;i<val;i++)
inorder[i]=sc.nextInt();
bt.root=bt.buildBSTfromInorder(inorder);
break;
//22.-| Construct BST from Inorder Sequence STARTS.publicNodebuildBSTfromInorder(intinorder[]) {
intn=inorder.length;
System.out.println("Your BST is ready PRESS 4 AND ENTER to view");
returnbuildBSTfromInorder(inorder,0,n-1);
}
privateNodebuildBSTfromInorder(int[] in, intsi, intei) {
if(si>ei)
returnnull;
intmidRoot=(si+ei)/2;
Noden=newNode(in[midRoot]);
n.left=buildBSTfromInorder(in,si,midRoot-1);
n.right=buildBSTfromInorder(in,midRoot+1,ei);
returnn;
}
//22.-| Construct BST from Inorder Sequence ENDS.
// Main function callingBSTbt=newBST(); //BST is a class containing all the above functionscase23:
System.out.println("No. of Nodes in your BST ?");
val=sc.nextInt();
preorder=newint[val];
System.out.println("Enter values in preorder sequence");
for(inti=0;i<val;i++)
preorder[i]=sc.nextInt();
bt.root=bt.buildBSTfromPreorder(preorder);
break;
//23.-| Construct BST from Preorder Sequence STARTS.publicNodebuildBSTfromPreorder(intpreorder[]) {
intlr=-1000;//left rangeintrr=1000;// right rangeSystem.out.println("Your BST is ready PRESS 4 AND ENTER to view");
returnbuildBSTfromPreorder(preorder, lr, rr);
}
intidx=0;
privateNodebuildBSTfromPreorder(int[] pre, intlr, intrr) {
if(idx>=pre.length || pre[idx]<lr || pre[idx]>rr)
returnnull;
Noden=newNode(pre[idx++]);
n.left=buildBSTfromPreorder(pre, lr, n.data);
n.right=buildBSTfromPreorder(pre, n.data, rr);
returnn;
}
//23.-| Construct BST from Preorder Sequence ENDS.
// Main function callingBSTbt=newBST(); //BST is a class containing all the above functionscase24:
System.out.println("No. of Nodes in your BST ?");
val=sc.nextInt();
postorder=newint[val];
System.out.println("Enter values in postorder sequence");
for(inti=0;i<val;i++)
postorder[i]=sc.nextInt();
bt.root=bt.buildBSTfromPostorder(postorder);
break;
//24.-| Construct BST from Postorder Sequence STARTS.publicNodebuildBSTfromPostorder(intpostorder[]) {
intlr=-1000;//left rangeintrr=1000;// right rangeidx=postorder.length-1;
System.out.println("Your BST is ready PRESS 4 AND ENTER to view");
returnbuildBSTfromPostorder(postorder, lr, rr);
}
privateNodebuildBSTfromPostorder(int[] post, intlr, intrr) {
if(idx<0 || post[idx]<lr || post[idx]>rr)
returnnull;
Noden=newNode(post[idx--]);
n.right=buildBSTfromPostorder(post, n.data, rr);
n.left=buildBSTfromPostorder(post, lr, n.data);
returnn;
}
//24.-| Construct BST from Postorder Sequence ENDS.