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