Leetcode 108 Convert Sorted Array to Binary Search Tree
2013-02-21 22:02
387 查看
//L108
//we could use d&c
//Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
//we could do it recursively
//pick the middle element as the root
//then pass the left to the sortedArrayToBST, the array is from 0 to mid-1
//pass the right to sortedArrayToBST, the array is from mid+1 the end
//when the str is empty, return NULL
//we could use d&c
//Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
//we could do it recursively
//pick the middle element as the root
//then pass the left to the sortedArrayToBST, the array is from 0 to mid-1
//pass the right to sortedArrayToBST, the array is from mid+1 the end
//when the str is empty, return NULL
class Solution { public: TreeNode* sortedArrayToBSTHelper(int* arr, int start, int end) { if (start <= end) { int len = end - start; int mid = start + len / 2; TreeNode* root = new TreeNode(arr[mid]); root->left = sortedArrayToBSTHelper(arr, start, mid - 1); root->right = sortedArrayToBSTHelper(arr, mid + 1, end); return root; } else return NULL; } TreeNode* sortedArrayToBST(vector<int> &num) { // Start typing your C/C++ solution below // DO NOT write int main() function if (num.empty()) return NULL; int arr[num.size()]; for (unsigned int i = 0; i < num.size(); i++) { arr[i] = num[i]; } return sortedArrayToBSTHelper(arr, 0, num.size() - 1); } };
相关文章推荐
- Java for LeetCode 108 Convert Sorted Array to Binary Search Tree
- [LeetCode 108] Convert Sorted Array to Binary Search Tree
- leetCode 108,109:Convert Sorted Array/List to Binary Search Tree
- [LeetCode108]Convert Sorted Array to Binary Search Tree
- [LeetCode]: 108: Convert Sorted Array to Binary Search Tree
- Leetcode 108 Convert Sorted Array to Binary Search Tree 将一个有序数组变成BST
- 【LeetCode】C# 108、Convert Sorted Array to Binary Search Tree
- [Leetcode 108, Meidum] Convert Sorted Array to Binary Search Tree
- leetcode(108):Convert Sorted Array to Binary Search Tree
- LeetCode 108 Convert Sorted Array to Binary Search Tree
- leetcode_question_108 Convert Sorted Array to Binary Search Tree
- leetcode108~Convert Sorted Array to Binary Search Tree
- [leetcode][108]. Convert Sorted Array to Binary Search Tree
- leetcode_108 Convert Sorted Array to Binary Search Tree
- leetcode 108 Convert Sorted Array to Binary Search Tree
- LeetCode 108: Convert Sorted Array to Binary Search Tree
- leetcode 108 Convert Sorted Array to Binary Search Tree
- Leetcode 108 Convert Sorted Array to Binary Search Tree
- leetcode[108]Convert Sorted Array to Binary Search Tree
- leetcode-108-Convert Sorted Array to Binary Search Tree