Convert Sorted List to Balanced BST
Posted 北叶青藤
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Convert Sorted List to Balanced BST相关的知识,希望对你有一定的参考价值。
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Example
2
1->2->3 => / \\
1 3
分析:
非常简单,用递归即可。需要注意返回mid node的时候,要把整个list分成两半。
public class Solution { public TreeNode sortedListToBST(ListNode head) { return helper(head, null); } public TreeNode helper(ListNode head, ListNode tail) { ListNode mid = middle(head, tail); if (mid == null) return null; TreeNode root = new TreeNode(mid.val); root.right = helper(mid.next, tail); root.left = helper(head, mid); return root; } private ListNode middle(ListNode head, ListNode tail) { if (head == tail) return null; ListNode slow = head, quick = head; while (quick != tail && quick.next != tail) { slow = slow.next; quick = quick.next.next; } return slow; } }
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 /** 10 * Definition for a binary tree node. 11 * public class TreeNode { 12 * int val; 13 * TreeNode left; 14 * TreeNode right; 15 * TreeNode(int x) { val = x; } 16 * } 17 */ 18 public class Solution { 19 public TreeNode sortedListToBST(ListNode head) { 20 if (head == null) return null; 21 ListNode mid = middle(head); 22 TreeNode root = new TreeNode(mid.val); 23 root.right = sortedListToBST(mid.next); 24 if (mid != head) { 25 root.left = sortedListToBST(head); 26 } 27 return root; 28 } 29 30 private ListNode middle(ListNode head) { 31 if (head == null || head.next == null) return head; 32 ListNode pre = null, slow = head, quick = head; 33 34 while(quick.next != null && quick.next.next != null) { 35 pre = slow; 36 slow = slow.next; 37 quick = quick.next.next; 38 } 39 40 if (pre != null) { 41 pre.next = null; // cut the list into halves. 42 } 43 return slow; 44 } 45 }
以上是关于Convert Sorted List to Balanced BST的主要内容,如果未能解决你的问题,请参考以下文章
109.Convert sorted list to BST
Convert Sorted List to Binary Search Tree
Convert Sorted List to Balanced BST
109. Convert Sorted List to Binary Search Tree