标签:
题目描述:(链接)
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
解题思路:
1 /** 2 * Definition for a binary tree node. 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>& nums) { 13 sortedArrayToBST(begin(nums), end(nums)); 14 } 15 private: 16 TreeNode* sortedArrayToBST(vector<int>::iterator begin, vector<int>::iterator end) { 17 auto len = distance(begin, end); 18 if (len <= 0) return nullptr; 19 auto mid = begin + len / 2; 20 TreeNode *root = new TreeNode(*mid); 21 root->left = sortedArrayToBST(begin, mid); 22 root->right = sortedArrayToBST(mid + 1, end); 23 } 24 };
[LeetCode]Convert Sorted Array to Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/skycore/p/5055101.html