Convert sorted array to balanced binary search tree

If you want to practice data structure and algorithm programs, you can go through 100+ java coding interview questions.

In this post ,  we will see how to convert sorted array to balanced binary search tree.

Algorithm:

You might know that inorder traversal of binary search tree results in sorted array. We will use this property to convert sorted array to balanced binary search tree, so middle element of array or sub array will always be root for that array or subarray.

  • Initialise two variables start and end with 0 and arr.length -1.
  • Find middle element of array using start and end.
  • Make middle element root element of tree.
  • Recursively traverse left subtree, find middle and make it root node of left subtree
  • Recursively traverse right subtree, find middle and make it root node of right subtree.

Java code to convert sorted array to balanced binary search tree:

When you run above program, you will get below output:

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *