Leetcode | | 108. Convert Sorted Array to Binary Search Tree

Source: Internet
Author: User

Problem:

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

Hide TagsTree Depth-first SearchTest instructions: Converts an ascending sequence into a balanced lookup binary tree

Thinking:

(1) Balanced binary tree concept: The height difference of the left and right sub-tree can not exceed 1, find the concept of binary tree: Left child < parent < child

(2) Two-way recursive construction of two-fork tree

(3) The template function solves the formal parameter type Vector<int>::iterator is too long, the writing is inconvenient

Code

Class Solution {public  :      TreeNode *sortedarraytobst (vector<int> &num) {          if (num.size () ==0)              return NULL;          Return make (Num.begin (), Num.end ());                }      Template<class it>      TreeNode *make (it first,it last)      {          if (first==last)              return NULL;          It loc = first+ (Last-first)/2;          TreeNode *node = new TreeNode (*loc);          Node->left=make (first,loc);          Node->right=make (loc+1,last);          return node;      }  };


Leetcode | | 108. Convert Sorted Array to Binary Search Tree

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.