题目描述:
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()-1); } 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-1); return root; }
LeetCode:Convert Sorted Array to Binary Search Tree
原文地址:http://blog.csdn.net/yao_wust/article/details/40622807