一. 题目描述
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
二. 题目分析
这道题只要将列表转化为一个数组,就可以使用和题目Convert Sorted Array to Binary Search Tree一样的方法来进行,这种方法的时间复杂度为O(n)
,空间复杂度为O(n^2)
。
三. 示例代码
#include <iostream>
#include <vector>
using std::vector;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
struct TreeNode
{
int val;
TreeNode *left;