Convert Sorted Array to Binary Search Tree
2014.1.8 02:11
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Solution:
A height balanced binary tree is a binary tree, whose heights of left and right subtrees varie by at most 1. Thus constructing such a tree from a sorted array can be done by cutting the array by half and picking the middle element as the root.
Note that the inorder traversal of a BST is a sorted array, that should help you figure out how the method works.
Do this procedure recursively and the job is done.
Time and space complexities are both O(n), where n is the number of elements in the array. Space complexity comes from local parameters in function calls.
Accepted code:
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode *sortedArrayToBST(vector<int> &num) { 13 // Note: The Solution object is instantiated only once and is reused by each test case. 14 if(num.size() <= 0){ 15 return nullptr; 16 }else{ 17 return constructBSTFromArray(num, 0, (int)(num.size() - 1)); 18 } 19 } 20 private: 21 TreeNode *constructBSTFromArray(vector<int> &num, int left, int right) { 22 int mid; 23 TreeNode* root; 24 25 if(left > right){ 26 return nullptr; 27 } 28 29 mid = (right - left) / 2 + left; 30 root = new TreeNode(num[mid]); 31 root->left = constructBSTFromArray(num, left, mid - 1); 32 root->right = constructBSTFromArray(num, mid + 1, right); 33 34 return root; 35 } 36 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)