Tuesday, June 10, 2014

Convert (Sorted List || Sorted Array) to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
[Thoughts]: sorted 就是in order排序,设置全局变量,跟着走一遍
public class Solution {
    ListNode node = null;
    public TreeNode sortedListToBST(ListNode head) {
        if(head==null) return null;
        node = head;
        
        ListNode cur = head;
        int len = 0;
        
        while(cur!=null){
            cur = cur.next;
            len++;
        }
        
        return toBST(0, len-1); 
    }
    
    public TreeNode toBST(int start, int end){
        if(start>end)  return null;
        int middle = (start+end)/2;
        
        TreeNode left = toBST(start, middle-1);
        
        TreeNode root = new TreeNode(node.val);
        root.left = left;
        node = node.next;
        
        root.right = toBST(middle+1, end);
        return root;
    }   
}

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

public class Solution {
    public TreeNode sortedArrayToBST(int[] num) {
        if(num.length==0) return null;
        return toBST(num, 0 , num.length-1);
    }
    
    public TreeNode toBST(int[] num, int start, int end){
        if(start>end)
            return null;
        int middle = (start+end)/2;
        TreeNode root = new TreeNode(num[middle]);
        root.left = toBST(num, start, middle-1);
        root.right = toBST(num, middle+1, end);
        
        return root;
    }
}

No comments:

Post a Comment