首页 > 学院 > 开发设计 > 正文

108. Convert Sorted Array to Binary Search Tree

2019-11-10 18:38:12
字体:
来源:转载
供稿:网友

一开始以为是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); }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表