[LeetCode] Convert Sorted Array to Binary Search Tree

Posted gccbuaa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 108. Convert Sorted Array to Binary Search Tree

Leetcode 108. Convert Sorted Array to Binary Search Tree

LeetCode OJ 108. Convert Sorted Array to Binary Search Tree DFS求解

[LeetCode]题解(python):108-Convert Sorted Array to Binary Search Tree

LeetCode Convert Sorted List to Binary Search Tree

leetcode-algorithms-109. Convert Sorted List to Binary Search Tree