Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

DSA ASSIGNMENT-4

Name: V. Sai Nithin Reg No. 21BCE7120

1.Write a program to implement binary tree using linked list.


Code :
class TreeNode{
TreeNode leftBranch;
TreeNode rightBranch;
int data;
}
class Node{
int data;
Node next;
static Node head;
Node(int data){
this.data=data;
this.next=null;
}
public static void insert(int data){
Node newNode = new Node(data);
if(head == null){
head = newNode;
return;
}
newNode.next= head;
head=newNode;
}
}
class Tree extends Node{
static TreeNode headTree;
Tree(int data){
super(data);
}
public static void Inorder(TreeNode node){
if (node != null){
Inorder(node.leftBranch);
System.out.print(" "+ node.data);
Inorder(node.rightBranch);
}
}
public static void PreOrder(TreeNode node){
if(node != null){
System.out.print(" "+ node.data);
PreOrder(node.leftBranch);
PreOrder(node.rightBranch);
}
}

public static void PostOrder(TreeNode node){


if(node != null){
PostOrder(node.leftBranch);
PostOrder(node.rightBranch);
System.out.print(" "+ node.data);
}
}
public static void insertTree(int data){
TreeNode temp = headTree;
TreeNode branch = new TreeNode();
branch.data = data;
while(true){
if(temp == null){
headTree = branch;
break;
}
else if(temp.data > data){
if(temp.leftBranch == null){
temp.leftBranch = branch;
break;
}
temp = temp.leftBranch;
}
else if (temp.data < data) {
if(temp.rightBranch == null){
temp.rightBranch = branch;
break;
}
temp = temp.rightBranch;
}
}
}
public static void main(String[] args) {
insertTree(73);
insertTree(24);
insertTree(36);
insertTree(9);
insertTree(45);
Node node = head;
while(node != null){
insertTree(node.data);
node = node.next;
}
System.out.println("PreorderTraversal ");
PreOrder(headTree);
System.out.println("InorderTraversal ");
Inorder(headTree);
System.out.println("PostorderTraversal ");
PostOrder(headTree);
}
}
Output :
2. Write a program to implement binary tree traversals (Inorder,
Preorder, Postorder) using recursion.
Code :
Output :

You might also like