109. 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~100的数,这时进行数据查找的效率就要降低。

为了解决二叉排序树这种左右子树深度不均匀的情况引入了一种平衡二叉树(AVLTree):任何一个节点的左右子树深度差不超过1.通过这个限定,阻止了二叉树的左右子树深度差较大的情况,维持了二叉树的稳定。

 1     public TreeNode toBST(ListNode head, ListNode tail){
 2         if (head == tail) return null;
 3         ListNode slow = head,fast=head;
 4         while (fast!=tail && fast.next!=tail)
 5         {
 6             slow = slow.next;
 7             fast = fast.next.next;
 8         }
 9         TreeNode tree = new TreeNode(slow.val);
10         tree.left = toBST(head,slow);
11         tree.right = toBST(slow.next,tail);
12         return tree;
13     }
14     
15     public TreeNode sortedListToBST(ListNode head) {
16         if(head==null) return null;
17         return toBST(head,null);        
18     }

 

posted @ 2017-10-24 14:16  daniel456  阅读(107)  评论(0编辑  收藏  举报