题目描述
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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码
如果做了 98 题 和 99 题,那么又看到这里的升序数组,然后应该会想到一个点,二叉搜索树的中序遍历刚好可以输出一个升序数组。
所以题目给出的升序数组就是二叉搜索树的中序遍历。
根据中序遍历还原一颗树,又想到了 105 题 和 106 题,通过中序遍历加前序遍历或者中序遍历加后序遍历来还原一棵树。前序(后序)遍历的作用呢?提供根节点!然后根据根节点,就可以递归的生成左右子树。
这里的话怎么知道根节点呢?平衡二叉树,既然要做到平衡,我们只要把根节点选为数组的中点即可。
综上,和之前一样,找到了根节点,然后把数组一分为二,进入递归即可
#include <iostream>
#include <vector>
using namespace std;
/// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/// Recursion
/// Time Complexity: O(n)
/// Space Complexity: O(logn)
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
if(nums.size() == 0)
return NULL;
return buildTree(nums, 0, nums.size() - 1);
}
private:
TreeNode* buildTree(const vector<int>& nums, int l, int r){
if(l > r) return NULL;
if(l == r) return new TreeNode(nums[l]);
int mid = (l + r) / 2;
TreeNode* root = new TreeNode(nums[mid]);
root->left = buildTree(nums, l, mid - 1);
root->right = buildTree(nums, mid + 1, r);
return root;
}
};
int main() {
return 0;
}