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

lab5cFal12017 Lab 5c due october 25th 2017 by email. write a Binary Tree Program

ID: 3607016 • Letter: L

Question

lab5cFal12017 Lab 5c due october 25th 2017 by email. write a Binary Tree Program which implements an ordered binary (b) Prints the nodes of the tree level by 1eve1, from left to right. Root is level er Postorder and Inorder Traversal with the numbers shown below. create 0, the nodes immediatrely below root are at level 1 etc.Insert these numbers into the tree in order where al1 numbers to left are less than root and al1 numbers to the right are greater than root. 5, 6, 8, 12, 26, 14, 98, 88, 11, 29

Explanation / Answer

class Node<T> {
//The value present in the node.
public int value;

//The reference to the left subtree.
public Node left;

//The reference to the right subtree.
public Node right;

public Node(int value) {
this.value = value;
}

}
class BinarySearchTree {

//Refrence for the root of the tree.
public Node root;

public BinarySearchTree insert(int value) {
Node node = new Node<>(value);

if (root == null) {
root = node;
return this;
}

insertRec(root, node);
return this;
}

private void insertRec(Node latestRoot, Node node) {

if (latestRoot.value > node.value) {

if (latestRoot.left == null) {
latestRoot.left = node;
} else {
insertRec(latestRoot.left, node);
}
} else {
if (latestRoot.right == null) {
latestRoot.right = node;
} else {
insertRec(latestRoot.right, node);
}
}
}


/**
* Printing the contents of the tree in an inorder way.
*/
public void printInorder() {
printInOrderRec(root);
System.out.println("");
}

/**
* Helper method to recursively print the contents in an inorder way
*/
private void printInOrderRec(Node currRoot) {
if (currRoot == null) {
return;
}
printInOrderRec(currRoot.left);
System.out.print(currRoot.value + ", ");
printInOrderRec(currRoot.right);
}

public void printPreorder() {
printPreOrderRec(root);
System.out.println("");
}
private void printPreOrderRec(Node currRoot) {
if (currRoot == null) {
return;
}
System.out.print(currRoot.value + ", ");
printPreOrderRec(currRoot.left);
printPreOrderRec(currRoot.right);
}

public void printPostorder() {
printPostOrderRec(root);
System.out.println("");
}

private void printPostOrderRec(Node currRoot) {
if (currRoot == null) {
return;
}
printPostOrderRec(currRoot.left);
printPostOrderRec(currRoot.right);
System.out.print(currRoot.value + ", ");

}
}

public class lab5cFall2017 {

public static void main(String[] args) {
BinarySearchTree bst = new BinarySearchTree();
bst .insert(5)
.insert(6)
.insert(8)
.insert(12)
.insert(26)
.insert(14)
.insert(98)
.insert(88)
.insert(11)
.insert(29);
System.out.println("Inorder traversal");
bst.printInorder();

System.out.println("Preorder Traversal");
bst.printPreorder();

System.out.println("Postorder Traversal");
bst.printPostorder();

}
}