Question
Extend the code you wrote and implement the BST operations: search, insert, and (optional challenge) delete; AND Write a program that converts a sorted array
Extend the code you wrote and implement the BST operations: search, insert, and (optional challenge) delete; AND
Write a program that converts a sorted array to a balanced BST.
/*CODE*/
public class TreeHeight { public static class Node { int data; Node right; Node left; public Node(int data) { this.data = data; this.right = null; this.left = null; } } public Node root; public TreeHeight() { root = null; } public int findTreeHeight(Node temp) { if (root == null) { System.out.println("Tree is Empty."); return 0; } else { int rightHeight = 0, leftHeight = 0; if (temp.right != null) { rightHeight = findTreeHeight(temp.right); } if (temp.left != null) { leftHeight = findTreeHeight(temp.left); } int max = (rightHeight < leftHeight) ? rightHeight : leftHeight; return (max + 1); } } public static void main(String[] args) { TreeHeight th = new TreeHeight(); th.root = new Node(1); th.root.right = new Node(2); th.root.left = new Node(3); th.root.right.right = new Node(4); th.root.right.left = new Node(5); th.root.left.left = new Node(6); th.root.left.left.left = new Node(7); th.root.left.left.left.left = new Node(8); System.out.println("Maximum height of given tree: " + th.findTreeHeight(th.root); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started