Converts an ordered array in ascending order to a highly balanced binary search tree.
In this problem, a highly balanced binary tree refers to the absolute value of the height difference of the left and right two subtrees of each node of a binary tree not exceeding 1.
Example:
Given an ordered array: [ -10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which can be represented as the following highly balanced binary search tree:
0
/ \
-3 9
/ /
-10 5
See: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/
/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (NULL) , right (NULL) {}}; */class Solution {public: treenode* sortedarraytobst (vector<int>& nums) { int n=nums.size (); if (n==0| | Nums.empty ()) { return nullptr; } if (n==1) { return new TreeNode (Nums[0]); } int MID=N/2; Vector<int> Left (Nums.begin (), Nums.begin () +mid); Vector<int> Right (Nums.begin () +mid+1,nums.end ()); treenode* root=new TreeNode (Nums[mid]); Root->left=sortedarraytobst (left); Root->right=sortedarraytobst (right); return root; }};
108 convert Sorted array to Binary search tree converts an ordered array to a two-fork