Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Design a Binary Tree class that allows you to create and maintain trees with nodes whose data be a String. The class will have a

Design a Binary Tree class that allows you to create and maintain trees with nodes whose data be a String. The class will have a constructor that will receive as argument a string that it will be the data of the root node. The class will also have an addNode method that will receive as arguments two strings. The first string will be the data for the node that will be added and the second string will indicate the step that will be followed to locate the node. For example, if the string is "LRRL" will be interpreted that from the root we move the child by the side left, then go down on the right, on the right again and then on the left. In that position we will add the node. If the node would be a sheet then it is simply added. If the node would occupy the position of an existing node or if there is no One step to get to the indicated position the node is not added. Include in this class a toString method that One step to get to the indicated position the node is not added.

class BNode { int value; BNode leftPtr, rightPtr;

BNode(int v, BNode lft, BNode rght ) { value = v; leftPtr = lft; rightPtr = rght; }

BNode (int v) { this(v,null,null); }

void printTree() { System.out.println(value); if (this.leftPtr != null) { System.out.print(" "); printTree(this.leftPtr,2); } if (this.rightPtr != null) { System.out.print(" "); printTree(this.rightPtr,2); } }

protected void printTree(BNode ptr, int level) { System.out.println(ptr.value); if (ptr.leftPtr != null) { printSpaces(level); printTree(ptr.leftPtr,level + 1); } if (ptr.rightPtr != null) { printSpaces(level); printTree(ptr.rightPtr,level + 1); } }

protected void printSpaces(int spcs) { for (int i = 0; i < spcs; i++) { System.out.print(" "); } } } public class BinaryTreeDemo{ public static void main(String[] args){ BNode root = new BNode(4); root.leftPtr = new BNode(2); root.leftPtr.leftPtr = new BNode(1); root.leftPtr.rightPtr = new BNode(3); root.rightPtr = new BNode(5); root.rightPtr.rightPtr = new BNode(6); root.printTree(); } }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions

Question

4. What action should Cherita Howard take and why?

Answered: 1 week ago