码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]Convert Sorted List to Binary Search Tree

时间:2014-08-16 12:19:20      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   for   ar   

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 }

 

[leetcode]Convert Sorted List to Binary Search Tree,布布扣,bubuko.com

[leetcode]Convert Sorted List to Binary Search Tree

标签:style   blog   http   color   os   io   for   ar   

原文地址:http://www.cnblogs.com/huntfor/p/3916168.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!