二叉搜索树的递归运用
将一个有序排序链表转化为二叉平衡搜索树 思路来源于有序数组转换为此树很简单,就是数组的中点就是根节点,由此数组被分割为两部分,左边为左子树,右边为右子树,再在左边找中点就是左子树的根节点,由此形成递归。代码如下:
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
vector<int> nums;//将链表中的值放进向量对象中
ListNode *p=head;
while(p)
{
nums.push_back(p->val);
p=p->next;
}
return sortL(nums,0,nums.size()-1);
}
TreeNode *sortL(vector<int> &nums,int L,int R)
{
if(L>R) return NULL;//递归出口
int mid=(L+R)/2;
TreeNode *root=new TreeNode(nums[mid]);
root->left=sortL(nums,L,mid-1);
root->right=sortL(nums,mid+1,R);
return root;
}
};复制代码