Question: why is my code is not working import java.util.ArrayList; class TreeNode { E element; TreeNode left; TreeNode right; TreeNode ( E element ) { this.element
why is my code is not working import java.util.ArrayList;
class TreeNode
E element;
TreeNode left;
TreeNode right;
TreeNodeE element
this.element element;
this.left null;
this.right null;
class BinaryTree
TreeNode root;
public BinaryTree
this.root null;
public boolean insertE e
if root null
root new TreeNodee;
return true;
else
TreeNode parent null;
TreeNode current root;
while current null
parent current;
if ecompareTocurrentelement
current current.left;
else if ecompareTocurrentelement
current current.right;
else
return false; Duplicate node not inserted
if ecompareToparentelement
parent.left new TreeNodee;
else
parent.right new TreeNodee;
return true; element inserted successfully
Method to find depth of the tree
public int depthTreeNode node
if node null return ;
return Math.maxdepthnodeleft depthnoderight;
Method to find maximum value in the tree
public E maxTreeNode node
if node null return null;
E leftMax maxnodeleft;
E rightMax maxnoderight;
E max node.element;
if leftMax null && leftMax.compareTomax max leftMax;
if rightMax null && rightMax.compareTomax max rightMax;
return max;
Method to find the sum of all nodes
public double treeSumTreeNode node
if node null
return ;
return Double node.element treeSumnodeleft treeSumnoderight;
Method to find the average of all nodes
public double treeAverageTreeNode node, int count
if node null return ;
count;
return Double node.element treeAveragenodeleft, count treeAveragenoderight, count;
Method to check if the tree is balanced
public boolean isBalancedTreeNode node
if node null return true;
int leftDepth depthnodeleft;
int rightDepth depthnoderight;
return MathabsleftDepth rightDepthisBalancednodeleftisBalancednoderight;
public void buildfromnodelistsdouble pre, double in int size
public class BinaryTreeTest
public static void mainString args
Sample data arrays for preorder and inorder traversal
double pre;
double in;
BinaryTree tree new BinaryTree;
treebuildfromnodelistsprein;
int pre ; pre order
int in ;
in order
return buildfromnodelistspre in;
int size;
double pre;
double in
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
