Convert Sorted Array to Binary Search Tree

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Convert Sorted Array to Binary Search Tree相关的知识,希望对你有一定的参考价值。

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

 

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
 
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 
class Solution {
public:
    TreeNode *build(vector<int> &num, int l, int r) {
        if (l <= r)
        {
            int m = (l+r)/2;
            TreeNode *root = new TreeNode(num[m]);
            root->left = build(num,l,m-1);
            root->right = build(num,m+1,r);
            return root;
        }
        else
        {
            return NULL;
        }
        
    }
    TreeNode *sortedArrayToBST(vector<int> &num) {
        int n = num.size();
        if (n == 0)
            return 0;
        return build(num,0,n-1);
    }
};

 

以上是关于Convert Sorted Array to Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章

108. Convert Sorted Array to Binary Search Tree

Convert Sorted Array to Binary Search Tree

leetcode 108 Convert Sorted Array to Binary Search Tree

108. Convert Sorted Array to Binary Search Tree

108. Convert Sorted Array to Binary Search [Python]

LC.108.Convert Sorted Array to Binary Search Tree