标签:
比较直观的解法是自顶向下的递归解决,先找到中间节点作为根节点,然后递归左右两部分。所有我们需要先找到中间节点,题目中要求如果链表结点数为偶,则中间结点为两个中间结点的后一个。对于单链表来说,必须要遍历一边,可以使用快慢指针加快查找速度。
代码如下:
</pre>/** * 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) { if(head == null) return null; if(head.next == null){ return new TreeNode(head.val); } //用快慢指针找到中间节点 ListNode slow = head; ListNode fast = head;<p> ListNode preSlow = null;</p><p></p><p> /**//找到中间节点的前一个; * while(fast.next!=null&&fast.next.next!=null)</p><p> * {</p><p> * preslow=slow; * slow=slow.next; * fast=fast.next.next; * }</p><p> */</p><p></p> //找到中间节点的后一个; while(fast!= null&&fast.next!=null){ preSlow = slow; slow = slow.next; fast = fast.next; if(fast!=null&&fast.next!=null) { fast=fast.next; } } //分别递归左右两部分 TreeNode mid = new TreeNode(slow.val); if(preSlow != null){ preSlow.next = null; mid.left = sortedListToBST(head); } if(slow.next != null){ mid.right = sortedListToBST(slow.next); } return mid; }}<pre name="code" class="java">
标签:
原文地址:http://blog.csdn.net/jingsuwen1/article/details/51352747