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.

基本上是自己想的,只有一个地方参考了答案:就是如何记录链表中点前面那个点,也就是代码里的last这个ListNode应该怎么找到。

/**
 * 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; }
 * }
 */
class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if (head == null){
            return null;
        }
        return helper(head);
    }
    
    private TreeNode helper(ListNode head){
        if (head == null){
            return null;
        }
        if (head.next == null){
            return new TreeNode(head.val);
        }
        if (head.next.next == null){
            TreeNode root = new TreeNode(head.next.val);
            root.left = new TreeNode(head.val);
            return root;
        }
        ListNode fast, slow, last;
        fast = head;
        slow = head;
        last = head;
        while (fast.next != null && fast.next.next != null){
            last = slow;
            fast = fast.next.next;
            slow = slow.next;
        }
        fast = slow.next;
        last.next = null;
        TreeNode root = new TreeNode(slow.val);
        root.left = helper(head);
        root.right = helper(fast);
        return root;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容