Convert Sorted Array to Binary Search Tree
Given an array where elements is sorted in ascending order, convert it to a height balanced BST.
ideas:
Given an interval [left, right], take the element where the value mid= (left+right)/2 corresponds to the root of the binary tree. The value of the Zogen of the binary tree is similar to the result of the continue operation of [left, mid-1], right subtree.
The following:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode (int x): Val (x), left (null), right (null) {}
*};
*
/class Solution {public
:
treenode* generatebst (int left, int. right, vector<int>& num)
{
if (left > right)
return nullptr;
else if (left = right)
return new TreeNode (Num[left]);
else
{
int mid = (left + right)/2;
treenode* node = new TreeNode (Num[mid]);
Node->left = Generatebst (left, mid-1, num);
Node->right = Generatebst (mid + 1, right, num);
return node;
}
}
TreeNode *sortedarraytobst (vector<int> &num) {
return Generatebst (0, Num.size ()-1, num);
}
};