1、Java AC
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode sortedArrayToBST(int[] num) { if (num == null || num.length == 0) { return null; } int len = num.length; return createBSTree(num, 0, len - 1); } private TreeNode createBSTree(int[] num, int low, int high) { if (low > high) { return null; } if (low == high) { return new TreeNode(num[low]); } int mid = (low + high) >> 1; TreeNode root = new TreeNode(num[mid]); root.left = createBSTree(num, low, mid - 1); root.right = createBSTree(num, mid + 1, high); return root; } }2、1)Java AC
/** * 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; } int len = 0; List<Integer> list = new ArrayList<Integer>(); while(head != null){ list.add(head.val); head = head.next; len++; } return createBSTree(list, 0, len - 1); } private TreeNode createBSTree(List<Integer> list, int low, int high) { if (low > high) { return null; } if (low == high) { return new TreeNode(list.get(low)); } int mid = (low + high) >> 1; TreeNode root = new TreeNode(list.get(mid)); root.left = createBSTree(list, low, mid - 1); root.right = createBSTree(list, mid + 1, high); return root; } }2、2)Java AC
/** * 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; } return createBSTree(head, null); } private TreeNode createBSTree(ListNode start, ListNode end) { if(start == end){ return null; } ListNode fastNode = start; ListNode slowNode = start; while(fastNode != end && fastNode.next != end){ slowNode = slowNode.next; fastNode = fastNode.next.next; } TreeNode root = new TreeNode(slowNode.val); root.left = createBSTree(start, slowNode); root.right = createBSTree(slowNode.next, end); return root; } }