"Leetcode" Convert Sorted Array to Binary Search Tree (Easy)

Source: Internet
Author: User

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

Ordered array variable binary balance search tree, not difficult, recursive on the line. Each sequence establishes the root node (whichever is the most intermediate), then divides the left and right sub-trees with the sub-interval.

It's AC once.

Note: When the new struct is

struct TreeNode {     int  val;      * Left;      * Right;     TreeNode (  int  x): Val (x), left (null), right (null) {}};

To use TreeNode * root = new TreeNode (123); Be consistent with the form of the constructor.

#include <iostream>#include<vector>#include<algorithm>#include<queue>#include<stack>using namespacestd;//Definition for binary treestructTreeNode {intVal; TreeNode*Left ; TreeNode*Right ; TreeNode (intx): Val (x), left (null), right (null) {}};classSolution { Public: TreeNode*sortedarraytobst (vector<int> &num) {        if(Num.empty ()) {returnNULL; }        intNR = Num.size ()/2; TreeNode* Root =NewTreeNode (Num[nr]); Vector<int> numl (Num.begin (), Num.begin () +nr); Vector<int> Numr (Num.begin () + nr +1, Num.end ()); Root->left =Sortedarraytobst (NUML); Root->right =Sortedarraytobst (NUMR); returnRoot; }};intMain () {solution S; Vector<int>num; Num.push_back (1); Num.push_back (2); Num.push_back (3); Num.push_back (4); Num.push_back (5); Num.push_back (6); Num.push_back (7); TreeNode* ans =s.sortedarraytobst (num); return 0;}

"Leetcode" Convert Sorted Array to Binary Search Tree (Easy)

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.