Convert Sorted List to Binary Search Tree

来源:互联网 发布:sqlserver 商业智能 编辑:程序博客网 时间:2024/06/02 05:32


soln recursive 解法

public class Solution {

    static ListNode head; // must add this
    
    public TreeNode sortedListToBST(ListNode head) {
        if(head==null) return null;
        this.head=head;
        
        ListNode t=head;
        int len=0;
        while(t!=null){
            len++;
            t=t.next;
        }
        
        if(len==1) {
            TreeNode rootn = new TreeNode(head.val);
            return rootn;
        }
        
        return sortedListToBST(0,len-1,head);
    }
        
        private TreeNode sortedListToBST(int start, int end, ListNode node) {
            if(start>end) return null;
            ListNode tmp = node;
            int mid = start +(end-start)/2;
            for(int i=start;i<mid;i++){
                tmp=tmp.next;
            }
            
            TreeNode root=new TreeNode(tmp.val);
            TreeNode left = sortedListToBST(start,mid-1,node);
            root.left = left;
            TreeNode right = sortedListToBST(mid+1,end,tmp.next);
            root.right = right;
            return root;
        }
   
}
0 0