leetcode--Convert Sorted List to Binary Search Tree

来源:互联网 发布:matlab导入xlsx数据 编辑:程序博客网 时间:2024/06/05 01:58
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;}}

0 0