leetcode 108 Convert Sorted Array to Binary Search Tree
Posted GadyPu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 108 Convert Sorted Array to Binary Search Tree相关的知识,希望对你有一定的参考价值。
题目连接
https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
Convert Sorted Array to Binary Search Tree
Description
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) { int n = 0; if(!(n = nums.size())) return nullptr; nums.insert(nums.begin(), 0); function<TreeNode*(int , int)> built = [&](int l, int r)->TreeNode* { if(l > r) return nullptr; int m = (l + r) >> 1; TreeNode *x = new TreeNode(nums[m]); x->left = built(l, m - 1); x->right = built(m + 1, r); return x; }; return built(1, n); } };
以上是关于leetcode 108 Convert Sorted Array to Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 108. Convert Sorted Array to Binary Search Tree
Leetcode 108. Convert Sorted Array to Binary Search Tree
LeetCode_108. Convert Sorted Array to Binary Search Tree
[LeetCode]题解(python):108-Convert Sorted Array to Binary Search Tree