Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Im kind of confused on recursion, how the returns work and such. Can someone hel

ID: 3547705 • Letter: I

Question

Im kind of confused on recursion, how the returns work and such. Can someone help me on these two problems? Thanks!

Write a recursive Java method that searches any binary tree with int data elements (not necessarily a binary search tree) to determine whether it contains a specific element. You are given a reference to the root node of the tree and and an int to search for. Return null if the value is not found, and a reference to the TreeNode containing the value if it is found. TreeNode search (TreeNode root, int key) { Write a recursive Java method that searches a binary search tree with int data elements to determine whether it contains a specific element. You are given a reference to the root node of the tree and and an int to search for. Return null if the value is not found, and a reference to the TreeNode containing the value if it is found. Your method should have a worst case time complexity of O(h) where h is the height of the tree. TreeNode search (TreeNode root, int key) {

Explanation / Answer

Here is how you would go about the second one:


public static boolean isElementinTree(int num, BinaryTreeNode root)

{

return root != null && (root.getData() == num ||

isElementInTree(num, root.getLeft()) ||

isElementInTree(num, root.getRight()));

}


This recursion checks whether the element matches the root. If yes, it return 'yes', else it checks the left and right child and so on.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote