Given an array where elements is sorted in ascending order, convert it to a height balanced BST.
Hide TagsTree Depth-first SearchMethod One: Recursive, also DFS
/** 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) { intSize =num.size (); if(Size = =0) returnNULL; returnSortedarraytobstinternal (NUM,0, Size-1); } TreeNode*sortedarraytobstinternal (vector<int> &num,intLowintHigh ) { //The code is very important, I.e:low = 4, hight = 5, mid = 4,//Would call sortedarraytobstinternal (num, 4, 3) if(Low >High )returnNULL; if(Low = =High )return NewTreeNode (Num[low]); intMid = (high-low)/2+Low ; TreeNode*root =NewTreeNode (Num[mid]); TreeNode*left = sortedarraytobstinternal (num, Low, mid-1); TreeNode*right = Sortedarraytobstinternal (num, mid +1, high); Root->left =Left ; Root->right=Right ; returnRoot; } };
[Leetcode] Convert Sorted Array to Binary Search Tree