leetcode_108. Convert an orderly array is a binary search tree

An ordered array in accordance with the ascending order, is converted to a highly balanced binary search tree.

In this problem, a highly balanced binary tree is a binary tree refers to the left and right sub-tree of each node is the height difference between the absolute value of not more than 1.

Example:

Given an ordered array: [-10, -3,0,5,9],

One possible answer is: [0, -3,9, -10, null, 5], it can be expressed below this height balanced binary search tree:
     0
    / \
  -39
  / /
-105

Analysis: The title requires a high degree balance and requires a binary search tree.
The nature of the subject and the ascending ordered array of the given binary search tree, can be drawn, for a given array section, the middle section of the digital section must be converted root tree, while the figure other numbers to the left of the left subtree configuration corresponding to the root node, the right side of the right subtree constituting empathy.
Then the height balancing requirements, can be drawn, for a given interval, in order to achieve high degree of balance must be cut from the intermediate points to achieve a substantially equal number of right and left digital to achieve highly balanced.
It follows that the algorithm.
Constructor recursive function, each configured to select a current digital intermediate node interval, and the left and right to call itself recursively sub-tree configuration. Null pointer is returned when the interval does not exist.

class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return makenode(nums,0,nums.size()-1);
    }
    
    TreeNode* makenode(vector<int>& nums,int start,int end){
        if(start>end) return nullptr;
        int mid = start + (end-start)/2;
        TreeNode* cur = new TreeNode(nums[mid]);
        cur->left = makenode(nums,start,mid-1);
        cur->right = makenode(nums,mid+1,end);
        return cur;
    }
};
Published 112 original articles · won praise 0 · Views 343

Guess you like

Origin blog.csdn.net/qq_37292201/article/details/103983296