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

[Leetcode] Convert Sorted List to Binary Search Tree

时间:2014-10-21 03:33:45      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   sp   div   on   

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

 

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; next = null; }
 7  * }
 8  */
 9 /**
10  * Definition for binary tree
11  * public class TreeNode {
12  *     int val;
13  *     TreeNode left;
14  *     TreeNode right;
15  *     TreeNode(int x) { val = x; }
16  * }
17  */
18 public class Solution {
19     public TreeNode sortedListToBST(ListNode head) {
20         return mySortedListToBST(head, getLength(head));
21     }
22 
23     private TreeNode mySortedListToBST(ListNode head, int length) {
24         // TODO Auto-generated method stub
25         if (head == null || length == 0)
26             return null;
27         if (length == 1)
28             return new TreeNode(head.val);
29         int mid = length / 2;
30         ListNode peak = head;
31         for (int i = 0; i < mid; ++i) {
32             peak = peak.next;
33         }
34         TreeNode root=new TreeNode(peak.val);
35         root.left=mySortedListToBST(head, mid);
36         root.right=mySortedListToBST(peak.next, length-mid-1);
37         return root;
38     }
39 
40     private int getLength(ListNode head) {
41         // TODO Auto-generated method stub
42         int length = 0;
43         while (head != null) {
44             head = head.next;
45             length++;
46         }
47         return length;
48 }
49 }

 

[Leetcode] Convert Sorted List to Binary Search Tree

标签:style   blog   color   io   ar   for   sp   div   on   

原文地址:http://www.cnblogs.com/Phoebe815/p/4039356.html

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