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
题意
由一个完全排序的数组构造一个平衡二叉查找树
题解
题目类型:分治+dfs
通常构造二叉查找树,只需要按照规则递归插入就可以了
如下
TreeNode * insert(TreeNode * root, int val) {
if (root == nullptr) return new TreeNode(val);
if (val < root->val) root->left = insert(root->left, val);
else root->right = insert(root->right, val);
return root;
}
由于平衡的关系,这样做显然是不行的
我们观察一下树的结构,发现,每个节点的左右子树合并构成的序列刚好被节点的值平分,那么整棵树可以看成是对排序的序列的划分,首先找出中间的值,把小于该值的数划分到左子树,其余在右子树,平衡二叉树可以自然构造出来。
代码如下
class Solution {
public:
TreeNode *sortedArrayToBST(vector<int> &num) {
if(num.size() == 0) return NULL;
if(num.size() == 1)
{
return new TreeNode(num[0]);
}
int middle = num.size()/2;
TreeNode* root = new TreeNode(num[middle]);
vector<int> leftInts(num.begin(), num.begin()+middle);
vector<int> rightInts(num.begin()+middle+1, num.end());
root->left = sortedArrayToBST(leftInts);
root->right = sortedArrayToBST(rightInts);
return root;
}
};