In java
1. Write a recursive algorithm to add all the elements of an array of n elements
2. Write a recursive algorithm to get the minimum element of an array of n elements
3. Write a recursive algorithm to add the corresponding elements of two arrays (A and B) of n elements. Store the results in a third array C.
4. Write a recursive algorithm to get the maximum element of a binary tree
5. Write a recursive algorithm to get the number of elements of a binary tree
1. Write a recursive algorithm to add all the elements of an array of n elements
static int Cal_Sum(int arr[], int n)
{
if (n <= 0) // base condition
return 0;
return (Cal_Sum(arr, n - 1)+arr[n - 1]); // recursive call
}
2. Write a recursive algorithm to get the minimum element of an array of n elements
public static int find_MAX(int arr[], int n)
{
if(n == 1) // base condition
return arr[0];
return Math.max(arr[n-1], find_MAX(arr, n-1)); //recursive call
}
3. Write a recursive algorithm to add the corresponding elements of two arrays (A and B) of n elements. Store the results in a third array C.
static int[] fun(int a[], int b[],int c[],int n)
{
if(n==0) //base condition
return c;
c[n-1]=a[n-1]+b[n-1]; //add sum to c array
return fun(a,b,c,n-1); //recursive call
}
4. Write a recursive algorithm to get the maximum element of a binary tree
static int MAX_ELEMENT(Node node)
{
if (node == null) // base condition
return Integer.MIN_VALUE;
int ans = node.data;
int left_ans = MAX_ELEMENT(node.left); //recursive call
int right_ans = MAX_ELEMENT(node.right); //recursive call
if (right_ans > ans) // finding max
ans = right_ans;
if (left_ans > ans) // finding max
ans = left_ans;
return ans;
}
5. Write a recursive algorithm to get the number of elements of a binary tree
static int Count_Nodes(Node root)
{
if(root==null) // base condition
return 0;
return (1 + Count_Nodes(root.left) + Count_Nodes(root.right)); //recursive call
}
If you have any doubt please ask in comment.
Get Answers For Free
Most questions answered within 1 hours.