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

leetcode--108. Convert Sorted Array to Binary Search Tree

2019-11-10 19:22:29
字体:
来源:转载
供稿:网友

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

题解

以序列的中间元素作为根,转换后的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) { return sortedArrayToBSTHelp(nums, 0, nums.size()); } TreeNode* sortedArrayToBSTHelp(vector<int>& nums, int l, int r){ if(l >= r) return NULL; int mid = (l + r) >> 1; TreeNode* root = new TreeNode(nums[mid]); root->left = sortedArrayToBSTHelp(nums, l, mid); root->right = sortedArrayToBSTHelp(nums, mid + 1, r); return root; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表