Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
把一个有序的数组转换为一颗平衡二叉搜索树。每次找到中间节点作为根节点,根节点左边部分转换为左子树,右边部分转换为右子树。代码如下:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public TreeNode sortedArrayToBST(int[] nums) { 12 if(nums.length == 0) return null; 13 return changeToBST(nums, 0, nums.length-1); 14 } 15 16 public TreeNode changeToBST(int[] nums, int left, int right){ 17 int mid = (right - left)/2 + left; 18 TreeNode root = new TreeNode(nums[mid]); 19 if(left==mid) root.left = null; 20 else root.left = changeToBST(nums, left, mid-1); 21 if(right==mid) root.right = null; 22 else root.right = changeToBST(nums, mid+1, right); 23 return root; 24 } 25 }
时间: 2024-10-13 02:17:47