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

Convert Sorted List to Balanced BST

时间:2016-07-03 07:03:00      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

Example

               2
1->2->3  =>   /              1   3

分析:
非常简单,用递归即可。但是如果list的size小于3,就直接创建tree。大于3才递归,否则递归会出错。并且,需要注意返回mid node的时候,要把整个list分成两半。

 1 /**
 2  * Definition for ListNode.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int val) {
 7  *         this.val = val;
 8  *         this.next = null;
 9  *     }
10  * }
11  * Definition of TreeNode:
12  * public class TreeNode {
13  *     public int val;
14  *     public TreeNode left, right;
15  *     public TreeNode(int val) {
16  *         this.val = val;
17  *         this.left = this.right = null;
18  *     }
19  * }
20  */ 
21 public class Solution {
22     /**
23      * @param head: The first node of linked list.
24      * @return: a tree node
25      */
26     public TreeNode sortedListToBST(ListNode head) {  
27         // if list‘s size is less than 3, create tree directly
28         if (head == null) return null;
29         if (head.next == null) return new TreeNode(head.val);
30         if (head.next.next == null) {
31             TreeNode root = new TreeNode(head.val);
32             root.right = new TreeNode(head.next.val);
33             return root;
34         }
35         
36         ListNode mid = center(head);
37         TreeNode root = new TreeNode(mid.val);
38         root.left = sortedListToBST(head);
39         root.right = sortedListToBST(mid.next);
40         
41         return root;
42     }
43     
44     public ListNode center(ListNode head) {
45         if (head == null || head.next == null)  return head;
46         ListNode slow = head;
47         ListNode pre = null;
48         ListNode quick = head;
49         while (quick.next != null && quick.next.next != null) {
50             pre = slow;
51             slow = slow.next;
52             quick = quick.next.next;
53         }
54         if (pre != null) {
55             pre.next = null;  // cut the list into two halves.
56         }
57         return slow;
58     }
59 }

转载请注明出处:cnblogs.com/beiyeqingteng/

Convert Sorted List to Balanced BST

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5636498.html

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