The instructions to answer my question are below in bulletpo
The instructions to answer my question are below in bulletpoints, and write the code in Java, thank you.
Search ID Binary Tree Array bullet The ID array my array contains a binary tree with the root at index = 0; bullet Write a while loop to search for the value in the variable key bullet Write an if-else to change the variable index to search the left or right child bullet When the loop completes index must be the slot that equals variable key bullet Do not declare the variable index, but do initialize and change it during the search. Implement the instructions above by placing your Code here: index =; while () {if () {} else {}}Solution
SOlution:
root of the tree : array position 1
root\'s left child : array position 2
root\'s right child : array position 3
and so on...
___________________________________________
package com.chegg;
public class MyFirstClass {
public static void main(String[] args) {
System.out.println(\"Welcome!\");
int arr[] = { 1, 2, 3, 4, 5, 10 , 20 , 30};
int pos = search(arr);
System.out.println(\"key found at \"+ pos + \" position(starts from 0) = \"+ arr[pos]);
}
private static int search(int[] arr) {
int index = 0;
int key = 10; // Need to search key in array.
int len = arr.length;
while (len >= 0) {
if (index%2 == 0) { //right side of tree
if(arr[index] == key)
break;
else
index++;
} else { //left side of tree
if(arr[index] == key)
break;
else
index++;
}
}
return index;
}
}
Output:
Welcome!
key found at 5 position(starts from 0) = 10
