LintCode 1359: Convert Sorted Array to Binary Search Tree

介绍如何将一个升序排列的数组转换为高度平衡的二叉搜索树,并提供具体的实现方法及示例。

1359 · Convert Sorted Array to Binary Search Tree
Algorithms
Easy

Description
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
Example 1:

Input: [-10,-3,0,5,9]
Output: [0,-3,9,-10,#,5]
Explanation:
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/
-3 9
/ /
-10 5

For this tree, you function need to return a tree node which value equals 0.
Example 2:

Input: [1,3]
Output: [3,1]
Explanation:
One possible answer is: [3,1], which represents the following height balanced BST:
3
/
1

For this tree, you function need to return a tree node which value equals 3.
Tags
Company
Airbnb

解法1:递归

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param nums: the sorted array
     * @return: the root of the tree
     */
    TreeNode* convertSortedArraytoBinarySearchTree(vector<int> &nums) {
        int len = nums.size();
        return helper(nums, 0, len - 1);
    }
private:
    TreeNode *helper(vector<int> &nums, int start, int end) {
        if (start > end) return nullptr;
        int mid = start + (end - start) / 2;
        TreeNode *root = new TreeNode(nums[mid]);
        root->left = helper(nums, start, mid - 1);
        root->right = helper(nums, mid + 1, end);
        return root;
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值