首页 > 代码库 > [LeetCode] Convert Sorted Array to Binary Search Tree

[LeetCode] Convert Sorted Array to Binary Search Tree

Convert Sorted Array to Binary Search Tree

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

解题思路:

题意为构建有序数组的二分查找树。

比較简单。用递归方法就可以,中间的元素作为根节点,前半部分作为左孩子树,右半部分作为右孩子树。

/**
 * 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) {
        return sortedArrayToBSTHelper(nums, 0, nums.size()-1);
    }
    
    TreeNode* sortedArrayToBSTHelper(vector<int>& nums, int start, int end){
        if(start>end){
            return NULL;
        }
        int middle = (start+end)/2;
        TreeNode* root = new TreeNode(nums[middle]);
        root->left = sortedArrayToBSTHelper(nums, start, middle - 1);
        root->right = sortedArrayToBSTHelper(nums, middle + 1, end);
        return root;
    }
};


[LeetCode] Convert Sorted Array to Binary Search Tree