leetcode------Convert Sorted List to Binary Search Tree

标题: Convert Sorted List to Binary Search Tree
通过率: 27.8%
难度: 中等

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         if(head==null)return null;

21         ListNode h=head;

22         int len=0;

23         while(h!=null){

24             len++;

25             h=h.next;

26         }

27         return creattree(head,0,len-1);

28         

29     }

30     public TreeNode creattree(ListNode head,int start,int end){

31         if(start>end)return null;

32         int mid=(start+end)/2;

33         ListNode tmp=head;

34         for(int i=start;i<mid;i++){

35             head=head.next;

36         }

37         TreeNode root=new TreeNode(head.val);

38         root.left=creattree(tmp,start,mid-1);

39         root.right=creattree(head.next,mid+1,end);

40         return root;

41         

42         

43     }

44 }

 

你可能感兴趣的:(Binary search)