Leetcode problem solution 108-convert an ordered array into a binary sort tree

Problem Description

Give you an integer array nums, where the elements have been arranged in ascending order, please convert it into a highly 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:
Insert picture description here

输入:nums = [-10,-3,0,5,9]
输出:[0,-3,9,-10,null,5]
解释:[0,-10,5,null,-3,null,9] 也将被视为正确答案:

Insert picture description here
Example 2:
Insert picture description here

输入:nums = [1,3]
输出:[3,1]
解释:[1,3] 和 [3,1] 都是高度平衡二叉搜索树。

Problem-solving ideas:

The in-order traversal of BST is in ascending order, so this question is equivalent to restoring the binary search tree based on the sequence of the in-order traversal. Therefore, we can take any element in the ascending sequence as the root node, build the left subtree with the ascending sequence on the left of the element, and build the right subtree with the ascending sequence on the right of the element, so that the tree obtained is a binary search tree , And because this question requires balance, we can select the middle element each time as our root node. In this way, the height difference between the left and right subtrees is less than or equal to 1, and this process is performed recursively, and finally a highly balanced binary sort tree can be obtained.
Note: In fact, the idea of ​​a half search decision tree is also used here. The half search compares the key to be searched with the value of the middle element each time. If it is less, search to the left of the middle element, otherwise, search to the right. In this way, the binary search process can actually be described by a binary tree, which is a highly balanced binary sort tree
Insert picture description here

Implementation code

class Solution {
    
    
    public int [] arr;      //保存原有序数组,避免数组传参
    public TreeNode genBinaryTree(int low,int high){
    
    
        //如果low>high,就没有元素,直接返回空即可
        if(low>high){
    
    
            return null;
        }
        //如果low==high,待处理序列只有一个元素,这个结点将被作为叶子结点,返回即可
        if(low==high){
    
    
            TreeNode p=new TreeNode(arr[low]);
            p.left=null;
            p.right=null;
            return p;
        }
        //否则,找到中间元素,然后构造根节点,然后继续完善该结点的左右子树
        int mid=(low+high+1)/2;
        TreeNode p=new TreeNode(arr[mid]);
        p.left=genBinaryTree(low,mid-1);
        p.right=genBinaryTree(mid+1,high);
        return p;
    }
    public TreeNode sortedArrayToBST(int[] nums) {
    
    
        int len=nums.length;
        arr=new int[len];
        for(int i=0;i<len;i++){
    
    
            arr[i]=nums[i];
        }
        return genBinaryTree(0,len-1);
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_39736597/article/details/113939053