LeetCode from time to time to brush the question --Convert Sorted Array to Binary Search Tree

Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if(nums.length==0){
            return null;
        }
        TreeNode head=helper(nums,0,nums.length-1);
        return head;
    }
    public TreeNode helper(int[] nums,int low,int high){
        if(low>high){
            return null;
        }
        int mid=(high+low)/2;
        TreeNode root=new TreeNode(nums[mid]);
        root.left=helper(nums,low,mid-1);
        root.right=helper(nums,mid+1,high);
        return root;
    }
}

Obviously, we have to sort the array, in order to get a balanced binary search tree, then we need to continue to take an intermediate node to the array. We can easily think of recursion, to keep the array is divided into two, the middle element of the array is assigned to the respective left and right node node, then the answer.

Published 173 original articles · won praise 110 · Views 100,000 +

Guess you like

Origin blog.csdn.net/qq_35564813/article/details/104736998