LeetCode:Convert Sorted Array to Binary Search Tree
来源:程序员人生 发布时间:2014-11-09 09:49:26 阅读次数:2945次
题目描写:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
思路:采取类似折半查找的方式找到当前根节点,则当前根节点左侧的属于它的左子树部份,当前根节点右侧的属于它的右子树部份。再采取一样的方法,递归地对当前根节点的左右子树做相同的处理。
代码:
TreeNode * Solution::sortedArrayToBST(vector<int> &num)
{
if(num.size() == 0)
return NULL;
return sortedArrayToBSTCmp(num,0,num.size()⑴);
}
TreeNode * Solution::sortedArrayToBSTCmp(vector<int> &num,int head,int rear)
{
TreeNode * root = (TreeNode *)malloc(sizeof(TreeNode));
int mid = (head + rear) / 2;
root->val = num[mid];
if(mid + 1 <= rear)
root->right = sortedArrayToBSTCmp(num,mid+1,rear);
if(head <= mid - 1)
root->left = sortedArrayToBSTCmp(num,head,mid⑴);
return root;
}
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠