LeetCode 109 Convert Sorted List to Binary Search Tree

来源:互联网 发布:d3.js官网是什么 编辑:程序博客网 时间:2024/05/21 19:47

题目描述

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

分析

参考:LeetCode 108 Convert Sorted Array to Binary Search Tree

但是不能将linked list转换成arraylist,会超时。思路:快慢指针。

代码

    ListNode cutAtMid(ListNode head) {        if (head == null) {            return null;        }        ListNode fast = head;        ListNode slow = head;        ListNode pslow = head;        while (fast != null && fast.next != null) {            pslow = slow;            slow = slow.next;            fast = fast.next.next;        }        pslow.next = null;        return slow;    }    public TreeNode sortedListToBST(ListNode head) {        if (head == null) {            return null;        }        if (head.next == null) {            return new TreeNode(head.val);        }        ListNode mid = cutAtMid(head);        TreeNode root = new TreeNode(mid.val);        root.left = sortedListToBST(head);        root.right = sortedListToBST(mid.next);        return root;    }
0 0
原创粉丝点击