题目链接:108. 将有序数组转换为二叉搜索树 - 力扣(LeetCode) (leetcode-cn.com)
该问题的核心是弄清楚搜索树中序遍历得到的是一个有序的数组,所以从有序数组出发我们需要构建一棵二叉搜索树,又要保持平衡,因为选择中间数字作为根结点,根结点两边的树对应着数组中间位置左右两边的数组,依次递归来构建树便可以。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { // @Override // public String toString() { // return "TreeNode{" + // "val=" + val + // ", left=" + left + // ", right=" + right + // '}'; // } // } public TreeNode sortedArrayToBST(int[] nums) { return dfs(nums,0,nums.length-1); } private TreeNode dfs(int[] nums, int left, int right) { if (left > right) return null; int mid = (left + right) / 2; TreeNode treeNode = new TreeNode(nums[mid]); treeNode.left = dfs(nums,left,mid-1); treeNode.right = dfs(nums,mid+1,right); return treeNode; }}