using System; using System.Collections.Generic; /* public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode (int x) { val = x; } } */ class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @return TreeNode类 */ public TreeNode sortedArrayToBST (List<int> nums) { // write code here if (nums == null || nums.Count == 0) return null; if (nums.Count <= 1) return new TreeNode(nums[0]); return PartInitTree(nums, 0, nums.Count - 1); } public static TreeNode PartInitTree(List<int> nums, int nL, int nR) { if (nL > nR) return null; int nRootIndex = (int)Math.Ceiling((nR + nL) / 2.0); TreeNode treeNode = new TreeNode(nums[nRootIndex]); var t1 = PartInitTree(nums, nL, nRootIndex - 1); if (t1 == null) treeNode.left = t1; else { if (treeNode.val > t1.val) treeNode.left = t1; else treeNode.right = t1; } var t2 = PartInitTree(nums, nRootIndex + 1, nR); if (t2 == null) treeNode.right = t2; else { if (treeNode.val > t2.val) treeNode.left = t2; else treeNode.right = t2; } return treeNode; } }