[Leetcode 108]有序数组转BST二叉搜索树Convert Sorted Array to Binary Search Tree
题目
https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
Given an integer array nums
where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.
Example 1:
Input: nums = [-10,-3,0,5,9] Output: [0,-3,9,-10,null,5] Explanation: [0,-10,5,null,-3,null,9] is also accepted:
Example 2:
Input: nums = [1,3] Output: [3,1] Explanation: [1,3] and [3,1] are both a height-balanced BSTs.
思路
二叉搜索树:中序遍历生成的数组就是升序排列的
因为 depth of the two subtrees of every node never differs by more than one.高度差不超过1
我们以中间作为根节点,这样能尽量平衡,分成左右俩部分dfs即可
1 2 【3】 4 5
1 2 3 【4】 5 6
代码
class Solution { public TreeNode sortedArrayToBST(int[] nums) { if (nums.length==0){ return null; } return fun(nums,0,nums.length-1); } public TreeNode fun(int[] nums,int left,int right){ if(left>right) return null; int mid=left+(right-left)/2;//找到根节点 TreeNode root=new TreeNode(nums[mid]); //分成两个部分,[left,根节点-1][根节点+1,right] root.left=fun(nums,left,mid-1); root.right=fun(nums,mid+1,right); return root; } }