首页 > 其他 > 详细

109. Convert Sorted List to Binary Search Tree

时间:2017-10-24 14:36:58      阅读:221      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!