LINTCODE—排序列表转换为二分查找树
思路:主要就是用快慢指针找出中间点,作为一个伪“顶点”,然后递归调用自身,返回左右节点;
class Solution {
public:
/*
* @param head: The first node of linked list.
* @return: a tree node
*/
TreeNode * sortedListToBST(ListNode * head) {
// write your code here
if(head == NULL )
return NULL;
if(head -> next == NULL)
return new TreeNode(head -> val);
//快慢指针找到中间点
ListNode *slow = head ,*fast = head ,*temp = head;
while(fast != NULL && fast->next != NULL)
{
temp = slow;
slow = slow -> next;
fast = fast -> next -> next;
}
temp -> next = NULL;
// 递归调用自身
TreeNode *resTree = new TreeNode(slow -> val);
resTree -> left = sortedListToBST(head);
resTree -> right = sortedListToBST(slow -> next);
return resTree;
}
};