Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

i need arunning java code with commensts //////////////////////////////////// Bi

ID: 3847097 • Letter: I

Question

i need arunning java code with commensts

////////////////////////////////////

Binary Trees In this midterm, you will be dealing with binary trees. Binary trees are a way of storing data in a structured fashion, and are useful in many computer science applications. They are also great for recursion. A binary tree consists of a root Node, which starts the entire tree. The root node stores a positive integer named "data'. The root Node also points to two child Nodes, named "left" and "right'. These child Nodes, in turn, store a positive integer called "data", and point to two child Nodes, named "left" and "right". The following picture shows what a binary tree looks like: 840 11 35 82 The following code defines a BinaryTree class and a corresponding Node class that you can use for this midterm:

Explanation / Answer

class BinaryTree {
Node head;

public BinaryTree() {
this.head = new Node(0);
}

public BinaryTree(Node root) {
this.head = root;
}
  
  
// private sort method which calls private sort method
public boolean sort()
{
if(head!=null)
{
sort(head);
}
return true;
}
  
// Private recursive method
private void sort(Node n)
{
int t;
if(n.left!=null && n.right!=null)
{
if(n.left.data > n.right.data)
{
t= n.left.data;
n.left.data=n.right.data;
n.right.data=t;

}

sort(n.left); // sort left subtree
sort(n.right); // sort right subtree

}
}
  
  
// display tree Inorder
public void display(Node node)
{
if(node!=null)
{
if(node.left!=null)
display(node.left);
System.out.print(node.data+" ");

display(node.right);
}
}
}


class Node {
int data;
Node left;
Node right;

public Node(int data) {
this(data,null,null);
}

public Node(int data, Node left, Node right) {
this.data = data;
this.left = left;
this.right = right;
}
}
////////////////////////////////////
public class BinaryTreeTest {
public static void main(String[] args) {

Node root, left, right;

left = insertLR(new Node(5), new Node(8), new Node(3));
right = insertLR(new Node(11), new Node(82), new Node(35));
root = insertLR(new Node(840), left, right);

BinaryTree b = new BinaryTree(root);
  
b.sort();
b.display(root);
}

public static Node insertLR(Node root, Node left, Node right) {
root.left = left;
root.right = right;
return root;
}
}