109. Convert Sorted List to Binary Search Tree [Medium]

/**
 * 自己的代码
 * Runtime: 0 ms, faster than 100.00% 
 * Memory Usage: 39.6 MB, less than 88.37%
 */
class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        int cnt = 0; // count the number of nodes in the list
        ListNode p = head;
        while (p != null) {
            cnt++;
            p = p.next;
        }
        return helper(head, cnt);
    }
    private TreeNode helper (ListNode head, int len) {
        if (head == null || len <= 0) {
            return null;
        }
        ListNode mid = head;
        int leftSize = (len - 1) / 2;
        for (int i = 0; i < leftSize; i++) { // find the root node
            mid = mid.next;
        }
        TreeNode root = new TreeNode(mid.val);
        root.left = helper(head, leftSize);
        root.right = helper(mid.next, len - leftSize - 1);
        return root;
    }
}
/**
 * two pointers
 * Runtime: 0 ms, faster than 100.00%
 * Memory Usage: 39.8 MB, less than 82.43%
 */
class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        return helper(head, null);
    }
    private TreeNode helper(ListNode start, ListNode end) {
        if (start == end) {
            return null;
        }
        ListNode slow = start, fast = start;
        while (fast != end && fast.next != end) { // use two pointers to find the root val
            fast = fast.next.next;
            slow = slow.next;
        }
        TreeNode root = new TreeNode(slow.val);
        root.left = helper(start, slow);
        root.right = helper(slow.next, end);
        return root;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值