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

Problem Description

[https://leetcode.com/problems/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.

思路

遞歸,沒啥好說的。。。。

Code

package q109;

import TreeNode.*;

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}

public class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        return sortedListToBST(head, null);
    }
    public TreeNode sortedListToBST(ListNode head, ListNode end) {
        if (head == end)
            return null;
        if (head.next == end) {
            TreeNode root = new TreeNode(head.val);
            return root;
        }
        ListNode slow = head, fast = head;
        while (fast.next != end && fast.next.next != end) {
            slow = slow.next;
            fast = fast.next.next;
        }
        TreeNode root = new TreeNode(slow.val);
        root.right = sortedListToBST(slow.next, end);
        root.left = sortedListToBST(head, slow);
        return root;
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章