108.将有序数组转为二叉搜索树

mac2024-03-14  28

108.将有序数组转为二叉搜索树

这个题很好的考察了中序遍历的性质 答案不唯一,但是答案要求左右子树的高度差不超过1, 那么,我们可以用中间的数作为根节点,因为二叉搜索树的中序遍历一定是一个升序数组

class Solution { public TreeNode sortedArrayToBST(int[] nums) { if(nums==null) return null; return createNode(nums, 0, nums.length-1); } private TreeNode createNode(int[] nums,int l,int r) { if(l>r) return null; int m = l+((r-l)>>1); TreeNode root = new TreeNode(nums[m]); root.left = createNode(nums,l,m-1); root.right = createNode(nums,m+1,r); return root; } }
最新回复(0)