Given an array where elements is sorted in ascending order, convert it to a height balanced BST.
Idea: Convert a sorted array into a highly balanced two-fork search tree. The idea is to use the middle value as the root node, and then the left and right arrays are the left and right sub-trees. Recursive solution.
The code is as follows:
/** * Definition for a binary tree node. * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *} */public class Solution {public TreeNode sortedarraytobst (int[] nums) { /** * Highly balanced binary search tree * refers to the height difference of the left and right subtree not exceeding 1 * So every time from the middle tectonic root node * Both sides of the construction of the left and right subtree * /return BST (nums,0,nums.length-1); } Private TreeNode BST (int[] nums, int i, int j) {if (i > J) {return null;} int mid = (j + i + 1)/2; TreeNode root = new TreeNode (Nums[mid]); root.left = BST (nums,i,mid-1); Root.right = BST (nums,mid+1,j); return root;}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 108.Convert Sorted Array to Binary Search Tree (convert sorted array to BST) ideas and methods for solving problems