本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
Convert Sorted Array to Binary Search Tree
Total Accepted: 11817 Total Submissions: 37164Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
题意:将一个已排序的数组转化为一棵二叉查找树
思路:dfs + 二分
设数组的下标范围为[begin, end],它的中间元素的下标为middle = (begin + end) / 2;
middle 将数组分为[begin, middle - 1]和[middle + 1, end];
middle对应一个节点,它的左右子节点分别为[begin, middle - 1]和[middle + 1, end]的中间元素对应的节点
复杂度:时间O(log n),空间O(1)
/**
* 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 *sortedArrayToBST(vector<int> &num, int begin, int end){
if(begin > end) return NULL;
int middle = (begin + end) / 2;
TreeNode *root = new TreeNode(num[middle]);
root->left = sortedArrayToBST(num, begin, middle - 1);
root->right = sortedArrayToBST(num, middle + 1, end);
return root;
}
TreeNode *sortedArrayToBST(vector<int> &num){
return sortedArrayToBST(num, 0, num.size() - 1);
}
};