109. Convert Sorted List to Binary Search Tree
Posted andywu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了109. Convert Sorted List to Binary Search Tree相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章