您的位置:首页 > 编程语言

leetcode 109. Convert Sorted List to Binary Search Tree 源代码加详细思路和注释

2016-05-09 11:21 363 查看
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

Subscribe to see which companies asked this question
题目分析:将排好序的链表转换成平衡二叉树。我们想一下怎么将排好序的数组转换成平衡二叉树,首先找到根节点,之后递归的构建左右子树。那么转换为链表,怎么找到根节点,想到常用的链表思路:快慢指针,快速找到中间位置的根节点。
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head==null) return null;
if(head.next==null) return new TreeNode(head.val);
return toBST(head,null);

}

public TreeNode toBST(ListNode head,ListNode tail)
{
if(head==tail) return null; //head是起始节点,tail是终止结点的下一个结点
ListNode slow=head;
ListNode fast=head;
while(fast!=tail&&fast.next!=tail)//通过快慢指针快速找到根节点
{
fast=fast.next.next;
slow=slow.next;
}
TreeNode res=new TreeNode(slow.val);
res.left=toBST(head,slow);//递归的构建左子树,右子树
res.right=toBST(slow.next,tail);
return res;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 链表 BST