Table of contents
108. Convert ordered array to binary search tree
You are given an array of integers
nums
in which the elements are sorted in ascending order. Please convert it into a height-balanced binary search tree.A height-balanced binary tree is a binary tree that satisfies "the absolute value of the height difference between the left and right subtrees of each node does not exceed 1".
Example 1:
Input: nums = [-10,-3,0,5,9] Output: [0,-3,9,-10,null,5] Explanation: [0,-10,5,null,-3,null ,9] will also be considered the correct answer:Example 2:
Input: nums = [1,3] Output: [3,1] Explanation: [1,null,3] and [3,1] are both highly balanced binary search trees.hint:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums
Arrange in strict increasing order
Code:
/** * 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 { // 「每个节点的左右两个子树的高度差的绝对值不超过 1 」的二叉树 // 即将数组看作中序遍历[左根右],那么数组中间就看做根节点, // 递归处理:根据中序遍历确定根节点,然后递归确定左子树,右子树 public TreeNode sortedArrayToBST(int[] nums) { // 给出数组,本次需确定树的数组范围,初始为0——数组结束 return fun(nums,0,nums.length-1); } TreeNode fun(int[] nums,int beg,int end){ // 递归终止条件:该部分数组内容处理完了 if(beg>end) return null; // 按照中间(靠右)为根节点 int mid=(end-beg+1)/2+beg; // 确定当前范围根节点 TreeNode root=new TreeNode(nums[mid]); // 递归 root.left=fun(nums,beg,mid-1); root.right=fun(nums,mid+1,end); // 返回当前树 return root; } }
operation result: