【LeetCode】-- 108. Convert ordered array to binary search tree

1. Question

108. Convert ordered array to binary search tree - LeetCode

You are given an integer array nums, in which the elements have been 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".

2. Example

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

 

 

 

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

 

 

3. Analysis

When I see a binary tree, my first reaction is to use recursion.

To turn an ordered array into a binary tree, you need to find the root. The root is the number in the middle of the ordered array. The root divides the ordered array into two parts. The left side is the left subtree of the tree, and the right side is the right side of the tree. subtree, then find the root of the left subtree and the root of the right subtree. The root of the left subtree is the number in the middle of the left half of the array, and the root of the right subtree is the number in the middle of the right half of the array.

4. Code implementation

class Solution {
public:
    
    TreeNode* sortedArrayToBST(vector<int>& nums) 
    {
        return binaryTree(nums,0,nums.size() - 1);
    }
    
    //递归建立二叉树
    TreeNode* binaryTree(vector<int>& nums,int left,int right)
    {
        if(left > right)
        {
            return nullptr;
        }
        
        //计算根的数据值
        int mid = (left + right) / 2;
        
        //建二叉树
        TreeNode* root = new TreeNode(nums[mid]);
        root->left = binaryTree(nums,left,mid - 1);
        root->right = binaryTree(nums,mid + 1,right);

        return root;
    }
};

Guess you like

Origin blog.csdn.net/gx714433461/article/details/130006808