一开始以为是build平衡树,原来是给的vector是排序的,所以就简单好多
/** * 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* build(vector<int>& nums, int b, int e){ if(b > e) return NULL; int mid = (b + e) >> 1; TreeNode* root = new TreeNode(nums[mid]); root -> left = build(nums, b, mid - 1); root -> right = build(nums, mid + 1, e); return root; } TreeNode* sortedArrayToBST(vector<int>& nums) { if(nums.size() == 0) return NULL; return build(nums, 0, nums.size() - 1); }};新闻热点
疑难解答