leetcode--Convert Sorted List to Binary Search Tree
2015-06-13 21:23
337 查看
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode sortedListToBST(ListNode head) { ListNode t = head; int count = 0; while(t!=null){ count++; t = t.next; } int[] nums = new int[count]; t = head; int i=0; while(t!=null){ nums[i++] = t.val; t = t.next; } return helper(nums, 0, nums.length-1); } public TreeNode helper(int[] nums,int start,int end){ if(start>end) return null; if(start==end) return new TreeNode(nums[start]); int mid = start+(end-start)/2; TreeNode t = new TreeNode(nums[mid]); t.left = helper(nums, start, mid-1); t.right = helper(nums, mid+1, end); return t; } }
相关文章推荐
- EXP/IMP
- MVC大型商贸系统(库存管理)技术解释(六)商品返仓
- 删除一张表里重复的记录
- TCP紧急数据
- DataGridView中的常用技巧
- JAVA 面向对象和集合知识点总结
- 第三章 44题
- C++ const关键字总结
- QT TableWidget应用笔记
- Android之窗口样式设置
- 网络攻防之SQL注入攻击
- 一个Linux中用于监控的简易shell脚本
- 简单工厂模式与抽象工厂模式
- 小程序之计算器 【C++ STL栈实现】 + 【C 数组模拟栈实现】 【适用VC, DEV, codeblack】
- 【leetcode】Unique Binary Search Trees II
- js小结(一)
- Call to localhost/127.0.0.1:9000 failed on connection exception:java.net.ConnectException
- 简单理解——面向切面编程(AOP)
- js递归实现包名转换成对应的json对象
- 随机梯度下降(Stochastic gradient descent)和 批量梯度下降(Batch gradient descent )的公式对比、实现对比