一. 題目描述
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
#include
using std::vector;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
private:
TreeNode* sortedArrayToBST(vector::iterator Begin,
vector::iterator End)
{
if (Begin == End)
{
return NULL;
}
vector::iterator HeadIte = Begin + (End - Begin) / 2;
TreeNode *Head = new TreeNode(*HeadIte);
TreeNode *LeftChild = sortedArrayToBST(Begin, HeadIte);
TreeNode *RightChild = sortedArrayToBST(HeadIte + 1, End);
Head->left = LeftChild;
Head->right = RightChild;
return Head;
}
public:
TreeNode* sortedListToBST(ListNode* head)
{
vector Nums;
for (ListNode *TmpHead = head; TmpHead; TmpHead = TmpHead->next)
{
Nums.push_back(TmpHead->val);
}
return sortedArrayToBST(Nums.begin(), Nums.end());
}
};
四. 小結
以上所使用方法比較簡單,但還有可提升的空間。