[Leetcode] Convert Sorted array to binary search tree convert ordered array to binary

Source: Internet
Author: User

Given an array where elements is sorted in ascending order, convert it to a height balanced BST.

This problem is to turn an ordered array into a binary search tree, the so-called binary search tree, is always satisfied with the left < Root < right features, if the two-fork search tree by the middle sequence traversal, the result is an ordered array. So in turn, we can be informed that the root node should be an ordered array of intermediate points, from the middle point to the left and right two ordered arrays, in each of the points as the original middle point of the left or right two sub-nodes, this is not the core idea of binary search method. So this question is the two-point search method, the code is as follows:

/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: TreeNode*sortedarraytobst (vector<int> &num) {        returnSortedarraytobst (NUM,0, Num.size ()-1); } TreeNode*sortedarraytobst (vector<int> &num,intLeftintRight ) {        if(Left > right)returnNULL; intMid = (left + right)/2; TreeNode*cur =NewTreeNode (Num[mid]); Cur->left = Sortedarraytobst (num, left, mid-1); Cur->right = Sortedarraytobst (num, mid +1, right); returncur; }};

[Leetcode] Convert Sorted array to binary search tree convert ordered array to binary

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.