108 convert Sorted array to Binary search tree converts an ordered array to a two-fork

Source: Internet
Author: User

Converts an ordered array in ascending order to a highly balanced binary search tree.
In this problem, a highly balanced binary tree refers to the absolute value of the height difference of the left and right two subtrees of each node of a binary tree not exceeding 1.
Example:
Given an ordered array: [ -10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which can be represented as the following highly balanced binary search tree:
0
/ \
-3 9
/   /
-10 5
See: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/

/** * Definition for a binary tree node. * struct TreeNode {*     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode (int x): Val (x), left (NULL) , right (NULL) {}}; */class Solution {public:    treenode* sortedarraytobst (vector<int>& nums) {        int n=nums.size ();        if (n==0| | Nums.empty ())        {            return nullptr;        }        if (n==1)        {            return new TreeNode (Nums[0]);        }        int MID=N/2;        Vector<int> Left (Nums.begin (), Nums.begin () +mid);        Vector<int> Right (Nums.begin () +mid+1,nums.end ());        treenode* root=new TreeNode (Nums[mid]);        Root->left=sortedarraytobst (left);        Root->right=sortedarraytobst (right);        return root;    }};

108 convert Sorted array to Binary search tree converts an ordered array to a two-fork

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.