1. Write a function in Tree class which returns true if and only if the tree satisfies the binary search tree property.
The function’s header line is
public boolean isValidBST()
And in the attached code, you just need to finish the function after the comment: “//Instructor hint: please write your code here:”
Make sure you execute your code, and the result in the main function after calling your function should be same as the prompt message I write. Clearly you can add extra functions in the class to help you finish this function.
Use this code:
// tree.java
// demonstrates binary tree
// to run this program: C>java TreeApp
import java.io.*;
import java.util.*; // for Stack class
////////////////////////////////////////////////////////////////
class Node
{
public int iData; // data item (key)
public double dData; // data item
public Node leftChild; // this node's left child
public Node rightChild; // this node's right child
public void displayNode() // display ourself
{
System.out.print('{');
System.out.print(iData);
System.out.print(", ");
System.out.print(dData);
System.out.print("} ");
}
} // end class Node
////////////////////////////////////////////////////////////////
class Tree
{
private Node root; // first node of tree
// -------------------------------------------------------------
public Tree() // constructor
{ root = null; } // no nodes in tree yet
// -------------------------------------------------------------
public Node find(int key) // find node with given key
{ // (assumes non-empty tree)
Node current = root; // start at root
while(current.iData != key) // while no match,
{
if(key < current.iData) // go left?
current = current.leftChild;
else // or go right?
current = current.rightChild;
if(current == null) // if no child,
return null; // didn't find it
}
return current; // found it
} // end find()
// -------------------------------------------------------------
public void insert(int id, double dd)
{
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
if(root==null) // no node in root
root = newNode;
else // root occupied
{
Node current = root; // start at root
Node parent;
while(true) // (exits internally)
{
parent = current;
if(id < current.iData) // go left?
{
current = current.leftChild;
if(current == null) // if end of the line,
{ // insert on left
parent.leftChild = newNode;
return;
}
} // end if go left
else // or go right?
{
current = current.rightChild;
if(current == null) // if end of the line
{ // insert on right
parent.rightChild = newNode;
return;
}
} // end else go right
} // end while
} // end else not root
} // end insert()
// -------------------------------------------------------------
public void displayTree()
{
Stack<Node> globalStack = new Stack<Node>();
globalStack.push(root);
int nBlanks = 32;
boolean isRowEmpty = false;
System.out.println(
"......................................................");
while(isRowEmpty==false)
{
Stack<Node> localStack = new Stack<Node>();
isRowEmpty = true;
for(int j=0; j<nBlanks; j++)
System.out.print(' ');
while(globalStack.isEmpty()==false)
{
Node temp = (Node)globalStack.pop();
if(temp != null)
{
System.out.print(temp.iData);
localStack.push(temp.leftChild);
localStack.push(temp.rightChild);
if(temp.leftChild != null ||
temp.rightChild != null)
isRowEmpty = false;
}
else
{
System.out.print("--");
localStack.push(null);
localStack.push(null);
}
for(int j=0; j<nBlanks*2-2; j++)
System.out.print(' ');
} // end while globalStack not empty
System.out.println();
nBlanks /= 2;
while(localStack.isEmpty()==false)
globalStack.push( localStack.pop() );
} // end while isRowEmpty is false
System.out.println(
"......................................................");
} // end displayTree()
// -------------------------------------------------------------
public boolean isValidBST() {
return true;
}// end isValidBST()
// -------------------------------------------------------------
} // end class Tree
////////////////////////////////////////////////////////////////
public class TreeApp
{
public static void main(String[] args) throws IOException
{
int value;
Tree theTree = new Tree();
theTree.insert(50, 1.5);
theTree.insert(25, 1.2);
theTree.insert(75, 1.7);
theTree.insert(12, 1.5);
theTree.insert(37, 1.2);
theTree.insert(43, 1.7);
theTree.insert(30, 1.5);
theTree.insert(33, 1.2);
theTree.insert(87, 1.7);
theTree.insert(93, 1.5);
theTree.insert(97, 1.5);
theTree.displayTree();
System.out.println("It is a BST tree, after call your function, your result should be true: ");
System.out.println(theTree.isValidBST());
//Instructor: I change the node's value from 75 to 40, and now it is NOT a BST tree.
Node found = theTree.find(75);
found.iData = 40;
theTree.displayTree();
System.out.println("It is NOT a BST tree since one node's value is changed from 75 to 40, after call your function, your result should be false: ");
System.out.println(theTree.isValidBST());
} // end main()
// -------------------------------------------------------------
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
// -------------------------------------------------------------
public static char getChar() throws IOException
{
String s = getString();
return s.charAt(0);
}
//-------------------------------------------------------------
public static int getInt() throws IOException
{
String s = getString();
return Integer.parseInt(s);
}
// -------------------------------------------------------------
} // end class TreeApp
////////////////////////////////////////////////////////////////Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks
//completed code
// demonstrates binary tree
// to run this program: C>java TreeApp
import java.io.*;
import java.util.*; // for Stack class
////////////////////////////////////////////////////////////////
class Node {
public int iData; // data item (key)
public double dData; // data item
public Node leftChild; // this node's left child
public Node rightChild; // this node's right child
public void displayNode() // display ourself
{
System.out.print('{');
System.out.print(iData);
System.out.print(", ");
System.out.print(dData);
System.out.print("} ");
}
} // end class Node
// //////////////////////////////////////////////////////////////
class Tree {
private Node root; // first node of tree
// -------------------------------------------------------------
public Tree() // constructor
{
root = null;
} // no nodes in tree yet
// -------------------------------------------------------------
public Node find(int key) // find node with given key
{ // (assumes non-empty tree)
Node current = root; // start at root
while (current.iData != key) // while no match,
{
if (key < current.iData) // go left?
current = current.leftChild;
else
// or go right?
current = current.rightChild;
if (current == null) // if no child,
return null; // didn't find it
}
return current; // found it
} // end find()
// -------------------------------------------------------------
public void insert(int id, double dd) {
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
if (root == null) // no node in root
root = newNode;
else // root occupied
{
Node current = root; // start at root
Node parent;
while (true) // (exits internally)
{
parent = current;
if (id < current.iData) // go left?
{
current = current.leftChild;
if (current == null) // if end of the line,
{ // insert on left
parent.leftChild = newNode;
return;
}
} // end if go left
else // or go right?
{
current = current.rightChild;
if (current == null) // if end of the line
{ // insert on right
parent.rightChild = newNode;
return;
}
} // end else go right
} // end while
} // end else not root
} // end insert()
// -------------------------------------------------------------
public void displayTree() {
Stack<Node> globalStack = new Stack<Node>();
globalStack.push(root);
int nBlanks = 32;
boolean isRowEmpty = false;
System.out
.println("......................................................");
while (isRowEmpty == false) {
Stack<Node> localStack = new Stack<Node>();
isRowEmpty = true;
for (int j = 0; j < nBlanks; j++)
System.out.print(' ');
while (globalStack.isEmpty() == false) {
Node temp = (Node) globalStack.pop();
if (temp != null) {
System.out.print(temp.iData);
localStack.push(temp.leftChild);
localStack.push(temp.rightChild);
if (temp.leftChild != null || temp.rightChild != null)
isRowEmpty = false;
} else {
System.out.print("--");
localStack.push(null);
localStack.push(null);
}
for (int j = 0; j < nBlanks * 2 - 2; j++)
System.out.print(' ');
} // end while globalStack not empty
System.out.println();
nBlanks /= 2;
while (localStack.isEmpty() == false)
globalStack.push(localStack.pop());
} // end while isRowEmpty is false
System.out
.println("......................................................");
} // end displayTree()
// -------------------------------------------------------------
public boolean isValidBST() {
// calling helper method 1 to check if it is a valid bst, passing root
// node
return isValidBST(root);
}// end isValidBST()
// helper method 1 to check if it is a valid bst
private boolean isValidBST(Node node) {
// empty node is a valid bst
if (node == null) {
return true;
}
// if node is leaf, it is a valid bst
if (node.leftChild == null && node.rightChild == null) {
return true;
}
// getting value at current node
int value = node.iData;
// if any value left of node is bigger than current value, not a valid
// bst
if (node.leftChild != null && value <= max(node.leftChild)) {
return false;
}
// if any value right of node is smaller than current value, not a valid
// bst
if (node.rightChild != null && value >= min(node.rightChild)) {
return false;
}
// otherwise checking if left subtree is a valid bst and right subtree
// is a valid bst, returning true if both return true
return isValidBST(node.leftChild) && isValidBST(node.rightChild);
}
// helper method 2 to find the maximum value starting from a given node, to
// assist helper method 1
// pre condition: node is not null
private int max(Node node) {
// if this is leaf node, returning data
if (node.leftChild == null && node.rightChild == null) {
return node.iData;
}
// storing current value as maximum
int max_value = node.iData;
// if left node is not null,
if (node.leftChild != null) {
// calling max() method passing left node, and if the returned value
// is bigger than max_value, setting it as new max_value, otherwise
// no change
max_value = Math.max(max_value, max(node.leftChild));
}
// if right node is not null,
if (node.rightChild != null) {
// calling max() method passing right node, and if the returned
// value
// is bigger than max_value, setting it as new max_value, otherwise
// no change
max_value = Math.max(max_value, max(node.rightChild));
}
// returning the maximum value
return max_value;
}
// helper method 3, very similar to max, but finds minimum value instead.
// this is also to assist helper method 1
private int min(Node node) {
if (node.leftChild == null && node.rightChild == null) {
return node.iData;
}
int min_value = node.iData;
if (node.leftChild != null) {
min_value = Math.min(min_value, min(node.leftChild));
}
if (node.rightChild != null) {
min_value = Math.min(min_value, min(node.rightChild));
}
return min_value;
}
// -------------------------------------------------------------
} // end class Tree
// //////////////////////////////////////////////////////////////
public class TreeApp {
public static void main(String[] args) throws IOException {
int value;
Tree theTree = new Tree();
theTree.insert(50, 1.5);
theTree.insert(25, 1.2);
theTree.insert(75, 1.7);
theTree.insert(12, 1.5);
theTree.insert(37, 1.2);
theTree.insert(43, 1.7);
theTree.insert(30, 1.5);
theTree.insert(33, 1.2);
theTree.insert(87, 1.7);
theTree.insert(93, 1.5);
theTree.insert(97, 1.5);
theTree.displayTree();
System.out
.println("It is a BST tree, after call your function, your result should be true: ");
System.out.println(theTree.isValidBST());
// Instructor: I change the node's value from 75 to 40, and now it is
// NOT a BST tree.
Node found = theTree.find(75);
found.iData = 40;
theTree.displayTree();
System.out
.println("It is NOT a BST tree since one node's value is changed from 75 to 40, after call your function, your result should be false: ");
System.out.println(theTree.isValidBST());
} // end main()
// -------------------------------------------------------------
public static String getString() throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
// -------------------------------------------------------------
public static char getChar() throws IOException {
String s = getString();
return s.charAt(0);
}
// -------------------------------------------------------------
public static int getInt() throws IOException {
String s = getString();
return Integer.parseInt(s);
}
// -------------------------------------------------------------
} // end class TreeApp
// //////////////////////////////////////////////////////////////
/*OUTPUT*/
......................................................
50
25 75
12 37 -- 87
-- -- 30 43 -- -- -- 93
-- -- -- -- -- 33 -- -- -- -- -- -- -- -- -- 97
......................................................
It is a BST tree, after call your function, your result should be true:
true
......................................................
50
25 40
12 37 -- 87
-- -- 30 43 -- -- -- 93
-- -- -- -- -- 33 -- -- -- -- -- -- -- -- -- 97
......................................................
It is NOT a BST tree since one node's value is changed from 75 to 40, after call your function, your result should be false:
false
1. Write a function in Tree class which returns true if and only if the tree...
Start with the tree.java program (Listing 8.1) and modify it to create a binary tree from a string of letters (like A, B, and so on) entered by the user. Each letter will be displayed in its own node. Construct the tree so that all the nodes that contain letters are leaves. Parent nodes can contain some non-letter symbol like +. Make sure that every parent node has exactly two children. Don’t worry if the tree is unbalanced. Note that...
Need help in the below question. Answer in java Start with the tree.java program (Listing 8.1) and modify it to create a binary tree from a string of letters (like A, B, and so on) entered by the user. Each letter will be displayed in its own node. Construct the tree so that all the nodes that contain letters are leaves. Parent nodes can contain some non-letter symbol like +. Make sure that every parent node has exactly two children....
Using the following implementation of Tree class Node { public int iData; // data item (key) public double dData; // data item public Node leftChild; // this node's left child public Node rightChild; // this node's right child public void displayNode() // display ourself { System.out.print('{'); System.out.print(iData); System.out.print(", "); System.out.print(dData); System.out.print("} "); } } // end class Node //------------------------------------------------------------------ import java.io.IOException; import java.util.Stack; public class Tree { private Node root; // first node of tree // ------------------------------------------------------------- public Tree() // constructor { root = null; }...
Please I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to completely test every method in the BST class to ensure the class meets all its requirements. You should read the Listing 25.5: TestBST.java for an idea of what your program should look like. Listing 25.4 BST.java public class BST> extends AbstractTree { protected TreeNode...
Java binary search tree Add the following print method to the binary search tree class created in class (on D2L). This method should print all the nodes in the tree in level order (root first, then all children of root, then all children of those). Ensure your method runs in O(N), include comments to show how it conforms to this rule. Method header: public void printInLevelOrder() public class BinarySearchTree<E extends Comparable<? super E>> { private Node root; public BinarySearchTree() {...
3. (Gaddis Exercises 20.4) Tree Height Write a recursive member function for the BinaryTree class that returns the height of the tree. The height of the tree is the number of levels it contains. Demonstrate the function in a driver program. CPP FILE CODE: #include "BinaryTree.h" #include <iostream> using namespace std; BinaryTree::BinaryTree() { root = NULL; } BinaryTree::~BinaryTree() { destroy(root); } bool BinaryTree::search(int data) { return search(data, root); } void BinaryTree::insert(int data) { insert(data, root); } void BinaryTree::traverseInOrder() { traverseInOrder(root);...
In need of JAVA CODE FOR THIS OBJECTIVE: Modify the BST class I gave you as follows: In the case in which the deleted node has two children, write the code in two ways. a) always replace the deleted node with the largest node on the left. b) count how many deletions have been done, and for even deletions replace the deleted node with the largest node on the left, for odd deletions, replace the deleted node with the smallest...
Problem 2: based on java.util.LinkedList class, create MyStack class that should have the methods: push(), pop(), peek(), size(), isEmpty(). my linkedlist class is: public class Lab8_problem1 { private Node head, tail; private int size; public Lab8_problem1() { this.head = null; this.tail = null; this.size = 0; } //Insert a node at specifc Location public void insertAt(int value, int index) { Node newNode = new Node(); newNode.data = value; if(head == null){ head = newNode; tail = newNode; head.next...
Professionally and thoroughly comment on this code. //BinarySearchTree.java package Project.bst; //imports required import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; class BSTTreeNode{ BSTTreeNode left, right; String data; public BSTTreeNode(){ left = null; right = null; data = null; } public BSTTreeNode(String n){ left = null; right = null; data = n; } public void setLeft(BSTTreeNode n){ left = n; } public void setRight(BSTTreeNode n){ ...
Question - modify the code below so that for a node, the value of every node of its right subtree is less the node, and the value of each node of its left subtree is greater than the node. - create such a binary tree in the Main method, and call the following method: InOrder(Node theRoot), PreOrder(Node theRoot), PostOrder(Node theRoot), FindMin(), FindMax(), Find(int key) using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;...