Skip to content

Latest commit

 

History

History
81 lines (66 loc) · 1.96 KB

File metadata and controls

81 lines (66 loc) · 1.96 KB

108. Convert Sorted Array to Binary Search Tree

    1. Convert Sorted Array to Binary Search Tree [Tree] [Depth-first Search] [Easy]

Tags

  • [Tree] [Depth-first Search] [Easy]

Problem

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5

Data Structure

  • Tree

Algorithm/Method

  • Depth-first Search

Input

  • vector<int>& nums

Output

  • TreeNode*

Solution #1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        if (nums.empty()) return NULL;
        return sortedArrayToBST(nums.begin(), nums.end());
    }
    
private:
    template<typename Iter>
    TreeNode* sortedArrayToBST(Iter first, Iter last) {
        auto length = distance(first, last);
        if (length <= 0) return NULL;
        auto mid = first + length / 2;
        TreeNode* root = new TreeNode(*mid);
        root->left = sortedArrayToBST(first, mid);
        root->right = sortedArrayToBST(mid + 1, last);
        return root;
    }
};

Boudary Checking

  • if (nums.empty()) return NULL;

Time Complexity

  • $O(n)$

Space Complexity

  • $O(\log n)$

Notes

  • Use Divide and Conquer.

Mistakes

Related Problems

    1. Convert Sorted Array to Binary Search Tree [Tree] [Depth-first Search] [Easy]
    1. Convert Sorted List to Binary Search Tree [Linked List] [Depth-first Search] [Medium]