首页 > 代码库 > [leetcode]Convert Sorted List to Binary Search Tree
[leetcode]Convert Sorted List to Binary Search Tree
Convert Sorted List to Binary Search Tree
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
算法思路:
与[leetcode]Convert Sorted Array to Binary Search Tree很相似,不过一个是array,一个是list,无本质区别。
三步走:
找中点(快慢指针)
断链表(需要找慢指针的前驱)
分治。
代码如下:
1 public class Solution { 2 public TreeNode sortedListToBST(ListNode head) { 3 if(head == null) return null; 4 if(head.next == null) return new TreeNode(head.val); 5 ListNode hhead = new ListNode(0); 6 hhead.next = head; 7 ListNode fast = hhead, slow= hhead; 8 while(fast != null && fast.next != null){ 9 fast = fast.next.next;10 slow = slow.next;11 }12 TreeNode root = new TreeNode(slow.val);13 ListNode right = slow.next;14 ListNode pre = hhead;15 while(pre != null && pre.next != slow){16 pre = pre.next;17 }18 pre.next = null;19 ListNode left = hhead.next;20 root.left = sortedListToBST(left);21 root.right = sortedListToBST(right);22 return root;23 }24 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。