2014年5月9日星期五

Recursive Solution - Convert Sorted List to Binary Search Tree

The idea is to find the middle as the current root node, and curRoot.left = recursive call left half, and right = recursive call right half. Be careful of the loop/end node…

/**
 * 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) {
        if(head == null){
            return null;  
        }
        if(head.next == null){
            return new TreeNode(head.val);
        }
        return sortedListToBSTOps(head, null);
    }
   
    private TreeNode sortedListToBSTOps(ListNode begin, ListNode end){
        if(begin == null){
            return null;
        }
        if(begin == end){
           return new TreeNode(begin.val);
        }
        ListNode nextN = begin;
        ListNode nextNN = begin;
        ListNode preN = begin;
        while(nextNN != end && nextNN.next != end){
            preN = nextN;
            nextN = nextN.next;
            nextNN = nextNN.next.next;
        }
        TreeNode curNode = new TreeNode(nextN.val);
        if(nextN != begin)
            curNode.left = sortedListToBSTOps(begin, preN);
        if(nextN != end)  
            curNode.right = sortedListToBSTOps(nextN.next, end);
        return curNode;
    }
}

没有评论: