109. Convert Sorted List to Binary Search Tree

题目

原始地址:https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/#/description

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        
    }
}

描述

给定一个按照升序排序的单链表,将它转换成一个高度平衡的二叉搜索树。

分析

如果要保持二叉搜索树高度平衡,那么要求插入的顺序和二叉树按层遍历的顺序是一致的,也即每次都找到链表的中间节点并插入,并将中间节点的两侧分成两个子链表分别转换成中间节点的左右子树,如此递归进行。

解法

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        return insertNode(head, null);
    }

    private TreeNode insertNode(ListNode head, ListNode tail) {
        if (head == null || head == tail) {
            return null;
        }
        ListNode fast = head, slow = head;
        while (fast != tail && fast.next != tail) {
            fast = fast.next.next;
            slow = slow.next;
        }
        TreeNode root = new TreeNode(slow.val);
        root.left = insertNode(head, slow);
        root.right = insertNode(slow.next, tail);
        return root;
    }
}
posted @ 2017-05-08 19:01  北冥尝有鱼  阅读(144)  评论(0编辑  收藏  举报