码迷,mamicode.com
首页 > 其他好文 > 详细

Convert Sorted Array to Binary Search Tree & Convert Sorted List to Binary Search Tree

时间:2016-02-28 15:12:50      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

 

Subscribe to see which companies asked this question

 

要点就是找到中心点,然后分别递归构造左边的数和右边的数

TreeNode* sortedArrayToBST(vector<int>& nums, int beg, int end) {
    if (beg > end)
        return nullptr;
    int mid = (beg + end) >> 1;
    TreeNode* root = new TreeNode(nums[mid]);
    root->left = sortedArrayToBST(nums, beg, mid - 1);
    root->right = sortedArrayToBST(nums, mid + 1, end);
    return root;
    
}

TreeNode* sortedArrayToBST(vector<int>& nums) {
    return sortedArrayToBST(nums, 0, nums.size()-1);
}

链表为了代码的简洁,我使用了二级指针,不过可读性变差了

TreeNode* sortedListToBST(ListNode* head) {
    if (head == nullptr)
        return nullptr;
    ListNode* fast = head;
    ListNode** slow = &head;
    while (fast->next != nullptr && fast->next->next != nullptr)
    {
        fast = fast->next->next;
        slow = &((*slow)->next);
    }
    TreeNode* root = new TreeNode((*slow)->val);
    
    root->right = sortedListToBST((*slow)->next);
    *slow = nullptr;
    root->left = sortedListToBST(head);

    return root;
}

 

Convert Sorted Array to Binary Search Tree & Convert Sorted List to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/sdlwlxf/p/5224699.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!