Question: JAVA LANGUAGE Hi guys. Please help me to solve this question. I will upvote you if your answer is true. Thank you in advance! ----------------------------------------------------------------------------------------------------------
JAVA LANGUAGE
Hi guys. Please help me to solve this question. I will upvote you if your answer is true. Thank you in advance! ----------------------------------------------------------------------------------------------------------
Chapter tree. This is a part of code about binary search tree for level order. Please help me modify this code to avoid plagiarism. If you just simply change the variable name only, i will downvote you.
//BinaryTree.java
class Node {
int id;
Node left, right;
Node(int id) {
this.id = id;
left = null;
right = null;
}
}
public class BinaryTree {
Node root;
private Node insertHelper(Node current, int id) {
if (current == null) {
return new Node(id);
}
if (id < current.id) {
current.left = insertHelper(current.left, id);
} else if (id > current.id) {
current.right = insertHelper(current.right, id);
}
return current;
}
public void insert(int id) {
root = insertHelper(root, id);
}
public void inOrder(Node node) {
if (node != null) {
inOrder(node.left);
System.out.print(node.id + " ");
inOrder(node.right);
}
}
public void preOrder(Node node) {
if (node != null) {
System.out.print(node.id + " ");
inOrder(node.left);
inOrder(node.right);
}
}
public void postOrder(Node node) {
if (node != null) {
inOrder(node.left);
inOrder(node.right);
System.out.print(node.id + " ");
}
}
void levelOrder()
{
int h = height(root);
int i;
for (i = 1; i <= h; i++)
printCurrentLevel(root, i);
}
int height(Node root)
{
if (root == null)
return 0;
else {
int lheight = height(root.left);
int rheight = height(root.right);
if (lheight > rheight)
return (lheight + 1);
else
return (rheight + 1);
}
}
void printCurrentLevel(Node root, int level)
{
if (root == null)
return;
if (level == 1)
System.out.print(root.id + " ");
else if (level > 1) {
printCurrentLevel(root.left, level - 1);
printCurrentLevel(root.right, level - 1);
}
}
}
//BinaryTreeTest.java
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
