Home › Company-wise questions › Accenture › Convert Sorted Array to Binary Search Tree ← Accenture bank
Accenture · Question 50 · Trees
Convert Sorted Array to Binary Search Tree Trees C++ code ⏱ O(n) 💾 O(logn)
Service-based Published and maintained by DSA-topics · Last updated 30 November 2026 · Report an error
About this bank These are classic technical-interview concepts compiled from publicly circulated company-wise question sets, rewritten with original explanations and compiler-ready solutions for educational practice; inclusion does not imply endorsement by the company. Spotted an error? Tell us .
Problem Given a sorted array, convert it to a height balanced BST.
Approach Choose middle element as root recursively for balanced tree.
Time O(n)Space O(logn)
How it works 1 The middle element becomes the subtree root. 2 Halves recurse into balanced sides. Sample input / output Input:
nums = [-10, -3, 0, 5, 9]
Output:
[0, -10, 5, -3, 9] Constraints Sorted strictly increasing; 1 <= nums.length <= 10^4.
Solution — read it, then walk it Flowchart Pseudocode
Time O(n)Space O(logn)Loops 2Branches 3Returns 1source · C++
Scroll sideways for wide charts — the view follows the active step. ⤢ Expand
↻ repeat ↻ repeat START using namespace std CLASS TreeNode DEFINE val TreeNode *left, *right TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode* buildTree(const vector<int>& vs, int nullMark = INT_MIN) DEFINE printVec(const vector<int>& v) cout << "[" for (size_t i = 0; i < v.size(); ++i) if (i) cout << ", " cout << v[i] cout << "]" << endl TreeNode* sortedArrayToBST(vector<int>& nums, int left, int right) TreeNode* sortedArrayToBST(vector<int>& nums) DEFINE levelPrint(TreeNode* root) if (!root) { cout << "[]" << endl; return; } vector<TreeNode*> q = {root} vector<int> out size_t qi = 0 while (qi < q.size()) TreeNode* node = q[qi++] if (!node) continue out.push_back(node->val) q.push_back(node->left) q.push_back(node->right) printVec(out) DEFINE main() vector<int> nums = {-10, -3, 0, 5, 9} levelPrint(sortedArrayToBST(nums)) RETURN 0 END start / end statement condition loop returns definition← Q49 · Lowest Common Ancestor of a BST Q51 · Validate Binary Search Tree → Solution code Core logic highlighted in green
Language Python Java C++source C Core logic Full code Copy
Recommended resources Affiliate links · may earn us a commission
Classic DSA interview books The reference books interviewers themselves learned from — great next to the visualizers. See the books → Structured coding courses Video courses that pair well with visual practice — pick one language and go deep. Browse courses → Cloud hosting for side projects Ship the portfolio project that gets you hired — free credits for new accounts. Claim credits →