Question: DEsign a BinaryTree class that uses TreeNode to implement a binary tree. The class should contain a maximum() method that returns the element of the

DEsign a BinaryTree class that uses TreeNode to implement a binary tree. The class should contain a maximum() method that returns the element of the maximum ode of the tree.

Note that,the BinaryTree should be generic, so that it supports different type of elements in the tree node The generic type should be comparable, since we need to find out the maximum node from the tree.

You should implement the BinaryTree class to work my TestBinaryTree.java. In the test code, we create an integer binary tree and a character binary tree.

public class TestBinaryTree {

public static void main(String[] args){

//test case 1

//=================== Test Case 1 ===================

//The maximum node of the tree is 9

System.out.println("=================== Test Case 1 ===================");

BinaryTree bt = new BinaryTree<>();

BinaryTree.TreeNode[] nodes = new BinaryTree.TreeNode[10];

for(int i = 0; i<10; i++){

nodes[i] = new BinaryTree.TreeNode(i);

}

nodes[1].left = nodes[0];

nodes[1].right = nodes[3];

nodes[0].left = nodes[9];

nodes[0].right = nodes[8];

nodes[3].left = nodes[2];

nodes[3].right = nodes[4];

nodes[9].left = nodes[7];

nodes[8].right = nodes[6];

nodes[4].right = nodes[5];

bt.root = nodes[1];

System.out.println("The maximum node of the tree is "+bt.maximum());

//test case 2

//=================== Test Case 2 ===================

//The maximum node of the tree is g

System.out.println("=================== Test Case 2 ===================");

BinaryTree bt2 = new BinaryTree<>();

BinaryTree.TreeNode[] nodes2 = new BinaryTree.TreeNode[10];

for(int i = 0; i<7; i++){

nodes2[i] = new BinaryTree.TreeNode((char)(i+'a'));

}

nodes2[5].left = nodes2[1];

nodes2[5].right = nodes2[6];

nodes2[1].left = nodes2[3];

nodes2[1].right = nodes2[4];

nodes2[6].right = nodes2[0];

nodes2[6].left = nodes2[2];

bt2.root = nodes2[5];

System.out.println("The maximum node of the tree is "+bt2.maximum());

}

}

Note : you can't make any changes in the given TestBinaryTree code.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!