标签:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
思路:递归的思路。思路与重建二叉树类似。时间复杂度O(n), 空间复杂度O(logN)
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 if (num.empty()) return NULL; 14 return sortedArrayToBST(num, 0, num.size() - 1); 15 } 16 TreeNode* sortedArrayToBST(vector<int> &num, int start, int last) { 17 if (start > last) return NULL; 18 19 int half = (start + last) >> 1; 20 TreeNode* root = new TreeNode(num[half]); 21 root->left = sortedArrayToBST(num,start, half - 1); 22 root->right = sortedArrayToBST(num, half + 1, last); 23 24 return root; 25 } 26 };
[LeetCode] Convert Sorted Array to Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/vincently/p/4237216.html