LeetCode: Convert Sorted Array to Binary Search Tree (DFS using Binary Search techniques)

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/, problem statement:

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

Since the tree has to be height balanced, the array needs to be divided in half all the time in order to create the BST properly. It will be a standard DFS and as we go down split the array in half similar to binary search techniques. We only visit the elements of the array once, hence it is O(n). Code below, cheers, Marcelo.


    public class Solution
    {
        public TreeNode SortedArrayToBST(int[] nums)
        {
            return SortedArrayToBSTInternal(nums, 0, nums.Length - 1);
        }

        private TreeNode SortedArrayToBSTInternal(int[] nums, int left, int right)
        {
            //Bases: null and leaf
            if (nums == null || nums.Length == 0 || left > right) return null;
            if (left == right) return new TreeNode(nums[left]);

            //Induction
            int mid = (left + right) / 2;
            TreeNode node = new TreeNode(nums[mid]);
            node.left = SortedArrayToBSTInternal(nums, left, mid - 1);
            node.right = SortedArrayToBSTInternal(nums, mid + 1, right);
            return node;
        }
    }

Comments

  1. Thanks for sharing this classics of recursive algorithms, Marcelo! This time I won't even share my solution, since it's almost identical to yours, though, as always, it's more than 10x faster written in C++ (13ms) :) The only suggestion I have is to avoid a classical binary search overflow bug when computing mid - if left and right get large enough, their sum will overflow and mid will point at some bad spot. To avoid this, it's recommended to use int mid = left + (right - left) / 2.

    ReplyDelete
    Replies
    1. Indeed, either that or change the data type, but your math solution is definitely more elegant!

      Delete
    2. changing a data type is also a right thing to do, but unfortunately it means that fewer elements will fit into cache, which can negatively impact performance. Jon Bentley mentioned this bug in his awesome "Programming Pearls".

      Delete

Post a Comment

Popular posts from this blog

Changing the root of a binary tree

Prompt Engineering and LeetCode

ProjectEuler Problem 719 (some hints, but no spoilers)