【convert-sorted-array-to-binary-search-tree】

来源:互联网 发布:three.js 教程 pdf 编辑:程序博客网 时间:2024/05/29 18:17

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.


思路:和链表转化成平衡二叉树的思路一样,不过数组找中间位置比较简单

class Solution {public:TreeNode* sortedArrayToBST(vector<int>& num){if (num.empty()){return NULL;}return vecToBST(0, num.size()-1, num);}TreeNode* vecToBST(int low, int high, vector<int> v){int mid;mid = (low+high+1)/2;//找中间位置TreeNode* root = new TreeNode(v[mid]);if (mid-1>=low){root->left= vecToBST(low, mid-1, v);}if (mid+1<=high){root->right = vecToBST(mid+1, high, v);}return root;}};


原创粉丝点击