FTPrep, 109 Convert Sorted List to Binary Search Tree

来源:互联网 发布:矩阵怎么计算 编辑:程序博客网 时间:2024/06/05 15:11

把问题转化成108了,但是有没有直接从list 入手的方法呢? TODO

代码:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } *//** * Definition for a binary tree node. * 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;        List<Integer> list= new ArrayList<Integer>();        while(head!=null){            list.add(head.val);            head=head.next;        }        return generateBST(list, 0, list.size()-1);    }        public TreeNode generateBST(List<Integer> list, int low, int high){        if(low>high) return null;        int mid=(high+low)/2;        TreeNode root = new TreeNode(list.get(mid));        root.left= generateBST(list, low, mid-1);        root.right= generateBST(list, mid+1, high);        return root;    }        }


原创粉丝点击