Convert Sorted List to Binary Search Tree leetcode java


題目

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

 

題解

之前做過一道是從sorted array轉換到BinarySearchTree的,方法還是一樣二分法。但是構造樹的方法不是由頂至下了,是要由低至上的建立。

代碼如下:

 

 1      static ListNode h;
 2  
 3      public TreeNode sortedListToBST(ListNode head) {
 4          if (head ==  null)
 5              return  null;
 6             
 7         h = head;
 8         
 9          int len = 0;
10         ListNode temp = head;
11          while(temp !=  null){
12             len++;
13             temp = temp.next;
14         }   
15          return sortedListToBST(0, len - 1);
16     }
17  
18      public TreeNode sortedListToBST( int start,  int end) {
19          if (start > end)
20              return  null;
21          int mid = (start + end) / 2;
22         TreeNode left = sortedListToBST(start, mid - 1);
23         TreeNode root =  new TreeNode(h.val);
24         root.left = left;
25         h = h.next;
26         TreeNode right = sortedListToBST(mid + 1, end);
27         root.right = right;
28  
29          return root;
30     }

 

Reference: http://www.programcreek.com/2013/01/leetcode-convert-sorted-list-to-binary-search-tree-java/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM