6/01/2014

76. Convert Sorted List to Binary Search Tree

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; next = null; }
 * }
 */
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        return sort(head, null);
    }
   
    public TreeNode sort(ListNode head, ListNode end) {
        if (head==end) return null;
       
        ListNode mid = head;
        ListNode p = head;
       
        while (p!=end && p.next!=end) {
            mid = mid.next;
            p = p.next.next;
        }
       
        TreeNode root = new TreeNode(mid.val);
        root.left = sort(head, mid);
        root.right = sort(mid.next, end);
       
        return root;
    }
}

1 条评论:

  1. 1. how to find mid listNode: two pointers--> 1 step & 2 steps;
    2. recursive, similar to Q 23.

    回复删除