Leetcode: 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.

目前做法:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 /**
10  * Definition for a binary tree node.
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         return buildTree(head, null);
22     }
23     
24     public TreeNode buildTree(ListNode head, ListNode end) {
25         if (head == end) return null;
26         ListNode fast = head;
27         ListNode slow = head;
28         while (fast != end && fast.next != end) {
29             fast = fast.next.next;
30             slow = slow.next;
31         }
32         TreeNode root = new TreeNode(slow.val);
33         root.left = buildTree(head, slow);
34         root.right = buildTree(slow.next, end);
35         return root;
36     }
37 }

第一遍做法:难度70,与Convert Sorted Array to Binary Search Tree问题相似,这道题的做法就是,我们需要中点来做每一层树的根,问题在于,对于一个链表我们是不能常量时间访问它的中间元素的。于是我的想法是花O(N)的时间把链表里面的元素先存到一个数组或者ArrayList里面,这样就有了一个sorted的数组或者ArrayList,我们就很容易对它递归来建立一个height balanced BST

 Code Ganker有一个做法,整体过程就是一次中序遍历,时间复杂度是O(n),空间复杂度是栈空间O(logn)加上结果的空间O(n),额外空间是O(logn),总体是O(n)。代码如下:我的额外空间是O(N),他的做法比我优。

他的做法精髓在于:1. helper函数里递归实现了树的inorder访问,ArrayList<ListNode> list中list.get(0).val存的就是当前树inorder遍历正遍历到的节点其value值。我们依次把LinkedList里面的节点挨个添加到list.get(0),由于LinkedList是sorted的,所以LinkedList里面的点与BST inorder遍历的各个点是一一对应的,我们只需要用当前LinkedList节点的val去创建BST当前的节点就好了。

2. helper函数的 int l, int r看似不影响中序遍历,但是却帮助我们判断什么时候当前节点是null,作用就跟中序遍历递归写法里面的判空语句 if(root == null)return; 一样

 1 public TreeNode sortedListToBST(ListNode head) {
 2     if(head == null)
 3         return null;
 4     ListNode cur = head;
 5     int count = 0;
 6     while(cur!=null)
 7     {
 8         cur = cur.next;
 9         count++;
10     }
11     ArrayList<ListNode> list = new ArrayList<ListNode>();
12     list.add(head);
13     return helper(list,0,count-1);
14 }
15 private TreeNode helper(ArrayList<ListNode> list, int l, int r)
16 {
17     if(l>r)
18         return null;
19     int m = (l+r)/2;
20     TreeNode left = helper(list,l,m-1);
21     TreeNode root = new TreeNode(list.get(0).val);
22     root.left = left;
23     list.set(0,list.get(0).next);
24     root.right = helper(list,m+1,r);
25     return root;
26 }
原文地址:https://www.cnblogs.com/EdwardLiu/p/3961052.html