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

有序单链表转BST树+时间复杂度要求O(n)

时间:2015-04-16 01:33:11      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:遍历   递归   链表   时间复杂度   

问题描述

针对有序的数组或链表,要转为相对平衡的BST树时,通常有多种做法。
1. 对于有序的数组A,转为BST时,取数组中间元素A[m],转为根,然后递归转换A[1..m-1], A[m+1 .. n]即可。时间复杂度 T(n) = 2 * T(n/2) + O(1),得出T(n) = O(n)
2. 针对有序的链表,如果依据上述方法,也可以进行。然而要取到A[m]的话,则需要遍历n/2长度的数组,因此需要额外O(n)的时间来取到A[m]。因此时间复杂度为T(n) = 2 * T(n/2) + O(n),得出T(n) = n log (n)。
OK,问题来了,如果要使得有序链表转BST也是O(n)时间,该怎么处理?

解决方案

针对有序链表的问题,可以参照递归的方案解决。不同的是,在进行左半边递归的时候,同时更新单链表的head节点。
LinkNode *head作为参数输入时,当转换完成后,head要变成单链表的尾节点->next,即NULL。当每次处理完一个LinkNode节点时,head就要同样右移一个节点。具体如下所示:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <cstring>

using namespace std;
// 单链表的节点结构
struct LinkNode {
    int value;
    LinkNode *next;
    LinkNode(int v): value(v), next(NULL) {}
};
// BST的节点结构
struct BstNode {
    int value;
    BstNode *left, *right;
    BstNode (int v): value(v), left(NULL), right(NULL) {}
};

class Solution {
public:
    void solve() {
        // test case
        int arr[] = {1,2,3,4,5,6,7};
        LinkNode *head = NULL, *p = NULL;
        for (int i = 0; i < sizeof(arr)/sizeof(int); i++) {
            if (head == NULL) head = p = new LinkNode(arr[i]);
            else p->next = new LinkNode(arr[i]), p = p->next;
        }
        BstNode *root = convert(head, 0, sizeof(arr)/sizeof(int)-1);
        printBstNode(root);
        printf("\n");
    }

    // move ahead the head pointer when carrying out the inorder traversal.
    // in this way, we avoid n*log(n) time complexity
    BstNode *convert(LinkNode *&head, int s, int e) {
        BstNode *root = NULL;
        if (s > e) {
        } else if (s == e) {
            root = new BstNode(head->value);
            head = head->next;
        } else {
            int m = s + (e-s) / 2;
            BstNode *left = convert(head, s, m-1);
            root = new BstNode(head->value);
            head = head->next;
            BstNode *right = convert(head, m+1, e);
            root->left = left;
            root->right = right;
        }
        return root;
    }
    // for printing out the content of a BstNode tree, inorder printing
    void printBstNode(BstNode *root) {
        if (root == NULL) return;
        printBstNode (root->left);
        printf("%d ", root->value);
        printBstNode(root->right);
    }
};

int main() {
    Solution solution;
    solution.solve();
}

有序单链表转BST树+时间复杂度要求O(n)

标签:遍历   递归   链表   时间复杂度   

原文地址:http://blog.csdn.net/nisxiya/article/details/45066731

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