Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
从给定的有序链表生成平衡二叉树。
解题思路:最容易想到的就是利用数组生成二叉树的方法,找到中间节点作为二叉树的root节点,然后分别对左右链表递归调用分别生成左子树和右子树。时间复杂度O(N*lgN)
1 public class Solution { 2 3 public TreeNode sortedListToBST(ListNode head) { 4 return toBST(head,null); 5 } 6 private TreeNode toBST(ListNode head ,ListNode tail){ 7 if(head == tail) return null; 8 ListNode slow = head; 9 ListNode fast = head; 10 while(fast.next!=tail&& fast.next.next != tail) { 11 fast = fast.next.next; 12 slow = slow.next; 13 } 14 TreeNode root = new TreeNode(slow.val); 15 root.left = toBST(head,slow); 16 root.right = toBST(slow.next,tail); 17 18 return root; 19 } 20 21 }
空间为O(1)时间为O(n):
TreeNode *sortedListToBST(ListNode *head) { int len = 0; ListNode * node = head; while (node != NULL) { node = node->next; len++; } return buildTree(head, 0, len-1); } TreeNode *buildTree(ListNode *&node, int start, int end) { if (start > end) return NULL; int mid = start + (end - start)/2; TreeNode *left = buildTree(node, start, mid-1); TreeNode *root = new TreeNode(node->val); root->left = left; node = node->next; root->right = buildTree(node, mid+1, end); return root; }
参考:
http://blog.csdn.net/salutlu/article/details/24502109
http://blog.csdn.net/worldwindjp/article/details/39722643
https://www.nowcoder.com/questionTerminal/86343165c18a4069ab0ab30c32b1afd0