LeetCode 1382 Balance A Binary Search Tree

Victoria
2 min readJun 21, 2021

First thing to remember is that when we do inorder traversal on a Binary Search Tree (BST) we can get back a sorted array. Then based on this sorted array of tree nodes we can re-construct a balanced BST and return the node. However, this is a bit tricky because we cannot just start from the beginning and keep adding nodes because in that way the tree will not be balanced. What I learned from one of the LeetCode discussion is an elegant recursion solution:

recursively build a balanced BST from sorted array

The nice thing about this algo is that it takes the middle point and treat it as the root, then assign left and right node recursively. Therefore, every node that became the new root will actually always be the middle value one so the tree will not be unbalanced.

For example if we have an array like 2 4 5 7 8 9

In the first execution the left will be 2 and right will be 9 and middle will be 5. Then when we assign root.left we go into the next recursive call and left became 2 and right became 4 and middle became 2. Therefore, the new root which will be the left child of 5 is 2 and the right child of 2 will be 4. As we repeat the process we will get 8 to be the right child of 5 and 7&9 will be 8’s children.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Victoria
Victoria

Written by Victoria

"What if I fall?" "Oh my darling, but what if you fly?"

No responses yet

Write a response