[刷题]Convert Sorted List to Binary Search Tree

来源:互联网 发布:谷歌有哪些好软件? 编辑:程序博客网 时间:2024/05/23 23:10

[LintCode]Convert Sorted List to Binary Search Tree

/** * Definition for ListNode. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int val) { *         this.val = val; *         this.next = null; *     } * } * Definition of TreeNode: * public class TreeNode { *     public int val; *     public TreeNode left, right; *     public TreeNode(int val) { *         this.val = val; *         this.left = this.right = null; *     } * } */ public class Solution {    /**     * @param head: The first node of linked list.     * @return: a tree node     */    public TreeNode sortedListToBST(ListNode head) {          // 2015-08-19        if (head == null) {            return null;        }        if (head.next == null) {            return new TreeNode(head.val);        }        // 至少有两个节点        // 找到中间节点,左链表和右链表        ListNode midNode = devideList(head);        ListNode leftList = head;        ListNode rightList = midNode.next.next;        TreeNode root = new TreeNode(midNode.next.val);        midNode.next = null;        // 递归 生成树的左右分支        root.left = sortedListToBST(leftList);        root.right = sortedListToBST(rightList);                return root;    }        /**     * 分割链表,返回前链表的最后一个节点     * 举例(长度):     * 4->2,2      * 5->2,3     */    private ListNode devideList(ListNode head) {        if (head == null || head.next == null) {            return head;        }                ListNode fast = head.next;        ListNode slow = head;                while (fast.next != null && fast.next.next != null) {            fast = fast.next.next;            slow = slow.next;        }                return slow;    }}
这里需要说明一下divideList方法:
类似于findMid,将一个链表分成两个链表,但稍有不同

用法:
mid = divideList(head)
第二个链表mid.next
mid.next = null
第一个链表head

分割实例:

父链 -> 两个自链 -> 数(数字表示链表长度,o表示节点)
0 -> 0,0 -> #
1 -> 1,0 -> o,#,#
2 -> 1,1 -> o,o,#
3 -> 1,2 -> o,o,o
4 -> 2,2 -> o,o,o,o,#,#,#
5 -> 2,3 -> o,o,o,o,#,o,#
6 -> 3,3 -> o,o,o,o,o,o,#
7 -> 3,4 -> o,o,o,o,o,o,o
...

0 0