-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path108.convert-sorted-array-to-binary-search-tree.cpp
More file actions
69 lines (66 loc) · 1.72 KB
/
108.convert-sorted-array-to-binary-search-tree.cpp
File metadata and controls
69 lines (66 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
* @lc app=leetcode id=108 lang=cpp
*
* [108] Convert Sorted Array to Binary Search Tree
*
* https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/
*
* algorithms
* Easy (59.81%)
* Likes: 3453
* Dislikes: 260
* Total Accepted: 498.5K
* Total Submissions: 826.9K
* Testcase Example: '[-10,-3,0,5,9]'
*
* Given an array where elements are sorted in ascending order, convert it to a
* height balanced BST.
*
* For this problem, a height-balanced binary tree is defined as a binary tree
* in which the depth of the two subtrees of every node never differ by more
* than 1.
*
* Example:
*
*
* Given the sorted array: [-10,-3,0,5,9],
*
* One possible answer is: [0,-3,9,-10,null,5], which represents the following
* height balanced BST:
*
* 0
* / \
* -3 9
* / /
* -10 5
*
*
*/
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return helper(nums, 0, nums.size() - 1);
}
TreeNode* helper(vector<int>& nums, int left, int right) {
if (left > right)
return nullptr;
int mid = left + (right - left) / 2;
TreeNode* node = new TreeNode(nums[mid]);
node->left = helper(nums, left, mid - 1);
node->right = helper(nums, mid + 1, right);
return node;
}
};
// @lc code=end