題目來源:https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
問題描述
108. Convert Sorted Array to Binary Search Tree
Easy
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:
/ \
-3 9
/ /
-10 5
------------------------------------------------------------
題意
根據有序數組建立二叉搜尋樹,要求二叉樹的近似平衡性,即各個葉子節點的深度至多相差1.
------------------------------------------------------------
思路
遞歸
------------------------------------------------------------
代碼
/**
* 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 build(nums, 0, nums.size());
}
/**
* build subtree from nums[left:right]
* return:
* root node pointer of the subtree built
*/
TreeNode* build(vector<int>& nums, int left, int right) {
if (left == right) {
return NULL;
}
int mid = (left+right)/2;
TreeNode* root = new TreeNode(nums[mid]);
root->left = build(nums, left, mid);
root->right = build(nums, mid+1, right);
return root;
}
};