首页 > 代码库 > [LeetCode]109 Convert Sorted List to Binary Search Tree
[LeetCode]109 Convert Sorted List to Binary Search Tree
https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
http://fisherlei.blogspot.com/2013/01/leetcode-convert-sorted-list-to-binary.html
http://blog.csdn.net/worldwindjp/article/details/39722643
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; next = null; } * } */ /** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode sortedListToBST(ListNode head) { // Option A: TreeNode root = buildTop2Buttom(head, null); return root; } ////////////////////////// // Option A: Top to bottom // // Unlike sorted array, no random access. // But we still can follow the same strategy that: // Given head, find the mid. // O(n log n) private TreeNode buildTop2Buttom(ListNode start, ListNode end) { if (start == null || start == end) return null; if (start.next == end) return new TreeNode(start.val); ListNode mid = findMid(start, end); TreeNode root = new TreeNode(mid.val); root.left = buildTop2Buttom(start, mid); root.right = buildTop2Buttom(mid.next, end); return root; } // Find the mid node from ‘start‘(inclusive) to ‘end‘(exclusive) private ListNode findMid(ListNode start, ListNode end) { ListNode toReturn = null; ListNode s1 = start; ListNode s2 = start; while (s2 != null && s2 != end) { toReturn = s1; s1 = s1.next; s2 = s2.next; if (s2 == null || s2 == end) s2 = null; else s2 = s2.next; } return toReturn; } }
[LeetCode]109 Convert Sorted List to Binary Search Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。