Write a class definition for a TNode<T> class to represent a general binary tree
ID: 3618089 • Letter: W
Question
Write a class definition for a TNode<T> class to represent a general binary tree with the following methods (implementing TNodeInterface). The class should contain a constructor with one T parameter so that the new node contains the parameter as data.
Root
/
A1 A2
/ /
B1 B2 C1 C2
/ /
D1 D2 E1 E2
Also write a main method and call it TreeTest (although it should run correctly with any main method).
public interface TNodeInterface<T>{
// add a child as the last child of the current node
public void addChild(T newData);
//Return a String with the children of a node in parentheses.
//The driver program will give the following output for the above tree:
//Root(A1(B1(D1D2)B2(E1E2))A2(C1C2))
public String toString();
//Accessor method for the First Child of the current node
public TNode<T> getLeftChild();
//Accessor method for the Next Sibling of the current node
public TNode<T> getRightChild()
//Accessor method for the Data
public T getData()
}
Recommended private members are:
private String toString(TNode<T> ptr) { }
public interface TNodeInterface<T>
{
// add a child as the last child of the current node
public void addChild(T newData);
//Return a String with the children of a node in parentheses.
//The driver program will give the following output for the above tree:
//Root(A1(B1(D1D2)B2(E1E2))A2(C1C2))
public String toString();
//Accessor method for the First Child of the current node
public TNode<T> getLeftChild();
//Accessor method for the Next Sibling of the current node
public TNode<T> getRightChild();
//Accessor method for the Data
public T getData();
}
---------------------------
---------------------------------
public class TreeTest
{
public static void main(String[] args)
{
// Root
// /
Explanation / Answer
privateString toString(TNode ptr) { // break case: ptr isnull if(ptr==null) { return ""; } // do an in-ordertraversal to show the toString() of the left and right children tothe left and right of the data, respectively returntoString(ptr.getLeft()) +ptr.getData().toString() +toString(ptr.getRight()); }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.