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)