题意:一个单链表元素按升序排列,将它转变成一个二叉搜索树
思路:采用递归和自底向上的方法,先算出链表的长度,找出当前链表的中间节点,然后再递归左右的子链表。自底向上的方法则是在遍历链表的同时将节点插入树中。时间复杂度为O(N)。
代码:
TreeNode *sortedListToBST(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int len = calLen(head);
return sortedListToBST(head, 0, len - 1);
}
int calLen(ListNode *node)
{
int len = 0;
while(node)
{
len++;
node = node->next;
}
return len;
}
TreeNode * sortedListToBST(ListNode *& list, int start, int end) //list代表要遍历的链表,每生成一个节点向后移一位
{
if (start > end)
return NULL;
// same as (start+end)/2, avoids overflow
int mid = start + (end - start) / 2;
TreeNode *leftChild = sortedListToBST(list, start, mid-1); //对前半部分遍历,执行后,前面二分之一的节点已经生成完,list指向中间节点
TreeNode *parent = new TreeNode(list->val);
parent->left = leftChild;
list = list->next; //生成新的结点之后,后移一位
parent->right = sortedListToBST(list, mid+1, end); //对后半部分遍历,执行后,list指向end后一个节点
return parent;
}