[LeetCode] 109. Ordered list convert binary search tree ☆☆☆ (recursive)

description

Given a singly-linked list, wherein the elements sorted in ascending order, to convert it to a well-balanced binary search tree.

In this problem, a highly balanced binary tree is a binary tree refers to the left and right sub-tree of each node is the height difference between the absolute value of not more than 1.

Example:

Given ordered list: [-10, -3, 0, 5, 9],

One possible answer is: [0, -3, 9, -10, null, 5], it can be expressed below this height balanced binary search tree:

0
/ \
-3 9
/ /
-10 5

Resolve

Ordered list, balanced binary tree, it is natural to think of the list into two, which is about two parts of the intermediate node node. Recursively nodes to about 2 parts.

Code

Recursion

/**
 * 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 {
    //me
    public TreeNode sortedListToBST(ListNode head) {
        if (null == head) {
            return null;
        } else if (null == head.next) {
            return new TreeNode(head.val);
        }
        ListNode slow = head;
        ListNode fast = head;
        ListNode pre = head;
        while (fast != null && fast.next != null) {
            pre = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        pre.next = null;
        TreeNode root = new TreeNode(slow.val);
        root.left = sortedListToBST(head);
        root.right = sortedListToBST(slow.next);
        return root;
    }
}

Optimization points

Ordered lists can be converted to an ordered array, reduce the complexity of the query. Space for time solution.

Ordered list into a binary tree search

Guess you like

Origin www.cnblogs.com/fanguangdexiaoyuer/p/12155685.html