108. Convert Sorted Array to Binary Search Tree

2018/04/30 leetcode 共 862 字,约 3 分钟

Title

the problem link

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

有序数组变为二叉排序树,和构造二叉排序树是不太一样的撒

Solution

//cpp:
/**
 * 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* f(vector<int>& nums,int l,int r){
        if(l>r){
            return NULL;
        }
        int mid=(l+r+1)/2;
        TreeNode* t=new TreeNode(nums[mid]);
        if(l==r){
            return t;
        }
        t->left=f(nums,l,mid-1);
        t->right=f(nums,mid+1,r);
        return t;
    }
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return f(nums,0,nums.size()-1);
    }
};

Search

    Table of Contents