码迷,mamicode.com
首页 > 其他好文 > 详细

109. Convert Sorted List to Binary Search Tree

时间:2017-10-24 14:51:01      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:col   blog   elements   lin   div   asc   return   null   含义   

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

题目含义:给定一个升序的列表,够着一个平衡二叉树

 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     }

 

109. Convert Sorted List to Binary Search Tree

标签:col   blog   elements   lin   div   asc   return   null   含义   

原文地址:http://www.cnblogs.com/wzj4858/p/7723279.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!