LeetCode刷題記63-109. 有序連結串列轉換二叉搜尋樹【檢視解法】

鹹蛋黃麥芽糖小餅乾發表於2020-11-26

LeetCode刷題記63

109. 有序連結串列轉換二叉搜尋樹

題目
在這裡插入圖片描述

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode F(List<Integer> list, int l, int r) {
        if (l > r) {
            return null;
        }
        if (l == r) {
            return new TreeNode(list.get(l));
        }
        int m = (l + r) / 2;
        TreeNode root = new TreeNode(list.get(m));
        root.left = F(list, l, m - 1);
        root.right = F(list, m + 1, r);
        return root;
    }
    public TreeNode sortedListToBST(ListNode head) {
        List<Integer> list = new ArrayList<Integer>();
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }
        return F(list, 0, list.size() - 1);
    }
}

偷懶的做法就是把連結串列轉成陣列。
就和之前一個題目 (忘記了是哪一個)一樣的。
這個解法
比較好,mark一下。
5/5
63/150

相關文章