Question: Hi guys. This is the code about binary search tree. Please help me modify this code to avoid plagiarism. (you can modify If you just
Hi guys. This is the code about binary search tree. Please help me modify this code to avoid plagiarism. (you can modify If you just copypaste the other experts code or just simply change variable name only, I will surely downvote you. Thank you in advance.
Code:
Node.java
public class Node {
public int data;
public Node leftChild,rightChild;
public Node(int givenData){
this.data = givenData;
this.leftChild = null;
this.rightChild = null;
}
}
BinaryTree.java
import java.util.*;
public class BinaryTree {
public Node root;
BinaryTree(){
this.root = null;
}
private Node insertUtility(Node node,int givenData){
Node newNode = new Node(givenData);
if(node==null) return newNode;
if(node.data==givenData) return node;
else if(node.data>givenData){
node.leftChild = insertUtility(node.leftChild,givenData);
}else{
node.rightChild = insertUtility(node.rightChild,givenData);
}
return node;
}
public void insert(int givenData){
this.root = insertUtility(this.root,givenData);
}
public void inOrder(Node node){
if(node!=null){
inOrder(node.leftChild);
System.out.print(node.data+" ");
inOrder(node.rightChild);
}
}
public void preOrder(Node node){
if(node!=null){
System.out.print(node.data+" ");
preOrder(node.leftChild);
preOrder(node.rightChild);
}
}
public void postOrder(Node node){
if(node!=null){
postOrder(node.leftChild);
postOrder(node.rightChild);
System.out.print(node.data+" ");
}
}
public void levelOrder(){
Queue
queue.add(this.root);
while(!queue.isEmpty()){
Node current = queue.poll();
System.out.print(current.data+" ");
if(current.leftChild!=null){
queue.add(current.leftChild);
}
if(current.rightChild!=null){
queue.add(current.rightChild);
}
}
}
}
BinaryTreeTest :
public class BinaryTreeTest {
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.insert(17);
tree.insert(12);
tree.insert(22);
tree.insert(10);
tree.insert(14);
tree.insert(20);
tree.insert(27);
System.out.println("Pre-order Traversal: ");
tree.preOrder(tree.root);
System.out.println(" In-order Traversal: ");
tree.inOrder(tree.root);
System.out.println(" Post-order Traversal: ");
tree.postOrder(tree.root);
System.out.println(" Level-order Traversal: ");
tree.levelOrder();
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
