In this problem, you will write some Java code for simple operations on binary s
ID: 3757415 • Letter: I
Question
In this problem, you will write some Java code for simple operations on binary search trees where keys are integers. Assume you already have the following code and assume that the method bodies, even though not shown, are correct and implement the operations as we defined them in class. public class BinarySearchTreeNode public int key; public BinarySearchTreeNode left; public BinarySearchTreeNode right; public class BinarySearchTree private BinarySearchTreeNode root,; public void insert (int key) f... > public void delete (int key) f... > public boolean find(int key) ) a) Add a method public int keySum() to the BinarySearchTree class that returns the sum of all the keys in the tree. You will need an assistant/helper methodExplanation / Answer
//Call below function and pass the root node of binary search tree will give the sum of all keys
public int keySum(BinarySearchTreeNode root)
{
// Base Case: root is null then return 0
if (root==null)
return 0; //condition to break recursion
//To get each key we have to traverse the binary search tree
//We are doing inorder traverse first getting left node of tree
//then the root and then the right one and do sum
return keySum(root.left) + root.key +keySum(root.right);
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.