problem:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Depth-first Search Linked List
题意:给定一个递增的单链表,将其转换成平衡查找二叉树,这道题是上道题的变形
thinking:
(1)平衡二叉树的概念:左右子树的高度差最大不能超过1,查找二叉树的概念:左孩子<父节点<右孩子
(2)二分法递归构造二叉树,只是单链表用二分法有点不方便,每次寻找中间结点需要将指针游走到中间位置。
对于只有一个元素的结点,该题可以将元素保存到数组中再处理,利用顺序存储随机访问的优势降低时间复杂度。
(3)模板函数解决形参类型vector<int>::iterator 太长,书写不方便
code:
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
vector<int> num;
ListNode *ptr=head;
while(ptr!=NULL)
{
num.push_back(ptr->val);
ptr=ptr->next;
}
if(num.size()==0)
return NULL;
return make(num.begin(),num.end());
}
protected:
template<class it>
TreeNode *make(it first,it last)
{
if(first==last)
return NULL;
it loc = first+(last-first)/2;
TreeNode *node = new TreeNode(*loc);
node->left=make(first,loc);
node->right=make(loc+1,last);
return node;
}
};