problem
108. Convert Sorted Array to Binary Search Tree
code
/** * 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.size()==0) return NULL; if(nums.size()==1) return new TreeNode(nums[0]);// int mid = nums.size() / 2; TreeNode* root = new TreeNode(nums[mid]);// vector<int> left(nums.begin(), nums.begin()+mid);// vector<int> right(nums.begin()+mid+1, nums.end());// root->left = sortedArrayToBST(left); root->right = sortedArrayToBST(right); return root; } };
参考
1. leetcode_108_Convert Sorted Array to Binary Search Tree;
2. BST;
3. https://www.cnblogs.com/grandyang/p/4295245.html
4. https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/discuss/35246/Accepted-C++-recursive-solution-within-a-single-method
完