Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* sortedArrayToBST(vector<int>& nums) { if (nums.empty()) return nullptr; TreeNode *root = helper(nums, 0, nums.size()-1); return root; } TreeNode *helper(vector<int>& nums, int start, int end){ if (start > end) return nullptr; int mid = start + (end - start)/2; TreeNode *root = new TreeNode(nums[mid]); #指针new root->left = helper(nums, start, mid-1); root->right = helper(nums, mid+1, end); return root; } };
posted on 2016-08-30 17:20 Sheryl Wang 阅读(102) 评论(0) 编辑 收藏 举报