[Binary search tree] leetcode108: Convert ordered array is a binary search tree (easy)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_43152052/article/details/100189218

Title:
Here Insert Picture Description
Solution:
For this question, we need to analyze the relationship between binary search tree with a sorted array. First, all nodes in the left subtree of the binary search tree is less than the value of the root node, the corresponding element in an ordered array before the median was less than the median. Secondly, all the values of the right subtree of the node binary search tree root node is greater than a value, then the corresponding element in the sorted array is the median is greater than the median. Finally, each of the binary tree is a subtree binary sort tree, corresponding to each of the three adjacent elements of the array are ordered in ascending order.

Here Insert Picture Description

code show as below:

class Solution {
public:
    //题解:将二叉排序树的节点值映射到一条直线上可得到一个升序的数组,那么对于高度平衡的二叉排序树最中间的元素或最中间两个元素的其中一个就是根节点
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return sortedArrayToBST(nums,0,nums.size()-1);
        }
    //将数组划分为两个闭合区间,对于树的形成类似树的先序遍历(根左右),在每一个节点连接到上一个节点后,这个节点需要先链接它的左子节点再链接它的右子节点
    //最终会形成一颗向右倾斜的树,也就是最后一层或最后两层的所有节点中左节点为空
     TreeNode* sortedArrayToBST(vector<int>&nums,int left,int right)
    {
        if(right<left)return nullptr;
        int mid=left+((right-left)>>1);
        TreeNode* root=new TreeNode(nums[mid]);//根节点
        root->left=sortedArrayToBST(nums,left,mid-1);//左子树
        root->right=sortedArrayToBST(nums,mid+1,right);//右子树
        return root;
    }
};

Guess you like

Origin blog.csdn.net/qq_43152052/article/details/100189218