标签:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
这道题要求根据一个有序的数组建立一棵二叉排序树。
利用折半的思想,构造根节点,再递归构造左右子树。递归出口是数组中只含一个元素。
TreeNode *sortedArrayToBST(vector<int> &num) {
if (!num.size())
return NULL;
return buildBST(num, 0, num.size() - 1);
}
TreeNode* buildBST(vector<int> num, int l, int r){
if (l <= r){
int mid = (l + r) / 2;
TreeNode* root = new TreeNode(num[mid]);
root->left = buildBST(num, l, mid - 1);
root->right = buildBST(num, mid + 1, r);
return root;
}
else
return NULL;
}
[LeetCode]Convert Sorted Array to Binary Search Tree
标签:
原文地址:http://blog.csdn.net/kaitankedemao/article/details/45047695