LeetCode - Convert Sorted List to Binary Search Tree

1 minute read

Problem description

description

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

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

1
2
3
4
5
6
7
8
9
10
11
Given the sorted linked list: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5


Analysis

General idea is to use inorder traversal. But we need a input to control the traversal, either the TreeNode itself or the left and right boundary.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
 * 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 {
    ListNode head;
    public TreeNode sortedListToBST(ListNode head) {
        ListNode p = head;
        
        this.head = head;
        int size = 0;
        while(p!=null){
            p =p.next;
            size++;
        }
        
        return build(0, size - 1);
    }
    
    TreeNode build(int l, int h){
        if (l > h){
            return null;
        }
        
        int mid = l + (h-l) / 2;
        
        TreeNode left = build(l, mid - 1);
        TreeNode node = new TreeNode(head.val);
        head = head.next;
        TreeNode right = build(mid+1, h);
        
        node.left = left;
        node.right = right;
        
        return node;
    }
}

What to improve

  • when using traversal to build a tree, we can use low and high as the input of the traversal.