Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
将增序链表转换为均衡的二叉查找树 与数组转换相同 找到链表的中间结点 作为树的根节点进行赋值 再将链表以中间节点为界 分为左右子链表 进行递归赋值 代码如下:
public class Solution { public TreeNode sortedListToBST(ListNode head) { if(head==null)return null; ListNode nhead=new ListNode(0); nhead.next=head; ListNode pre=nhead; ListNode slow=head; ListNode fast=head; while(fast.next!=null&&fast.next.next!=null){ pre=pre.next; slow=slow.next; fast=fast.next.next; } ListNode right=slow.next; pre.next=null; ListNode left=nhead.next; TreeNode root=new TreeNode(slow.val); root.left=sortedListToBST(left); root.right=sortedListToBST(right); return root; } }
Convert Sorted List to Binary Search Tree
原文地址:http://blog.csdn.net/u012734829/article/details/42267303