二叉树广义表的序列化反序列化

今天突然想起来大学时候遗留的一个关于二叉树的问题,甚是挂怀,于是葛优瘫中惊坐起,怒而码之,所谓老·不码不舒服司机是也。

定义二叉树结构:

struct Node
{
    int data;
    Node* left;
    Node* right;
};
typedef struct Node *BiTree;

随机生成二叉树:

BiTree randomCreateTree() {
    int i;
    BiTree root = NULL;
    srand(time(NULL));
    for (i = 0; i < N; i++) {
        int randNum = rand() % 100;
        root = insert_node(root, randNum);
    }
    return root;
}

二叉树序列化为广义表:

char *printTreeToString(struct Node *pNode) {
    char *line = malloc(sizeof(char) * 1000);
    memset(line, 0, 1000);
    walkPrintTree(pNode, line);
    printf("the tree line is:\n%s\n", line);
    return line;
}

void walkPrintTree(BiTree pNode, char *line) {
    if (pNode != NULL) {
        sprintf(line, "%s%d", line, pNode->data);
        sprintf(line, "%s%c", line, '(');
        walkPrintTree(pNode->left, line);
        sprintf(line, "%s%c", line, ',');
        walkPrintTree(pNode->right, line);
        sprintf(line, "%s%c", line, ')');
    } else {
        sprintf(line, "%s%c", line, '#');
    }
}

广义表(仅限二叉树)字符串的反序列化:

BiTree parseLineToTree(char *line, int len) {
    int data, pos = 0, commetPos, lLen = 0, rLen = 0;
    BiTree lTree = NULL, rTree = NULL;
    char *lTreeStr = NULL;
    char *rTreeStr = NULL;
    pos = parseData(line, &data, len);
    if (pos > 0) {
        commetPos = findCommaPos(line, len);
        lTreeStr = line + pos;
        rTreeStr = line + commetPos + 1;
        lLen = (int) (rTreeStr - lTreeStr - 1);
        rLen = len - lLen - pos - 2;
        printf("commet pos is %d\n",commetPos);
        printLenStr(lTreeStr, lLen);
        printLenStr(rTreeStr, rLen);
        lTree = parseLineToTree(lTreeStr, lLen);
        rTree = parseLineToTree(rTreeStr, rLen);
        return makeTree(data, lTree, rTree);
    }
    return NULL;
}

int findCommaPos(char *line, int len) {
    int i, count = 0;
    char cc;
    for (i = 0; i < len; i++) {
        cc = line[i];
        if (cc == '(') {
            count++;
        } else if (cc == ')') {
            count--;
            if (count == 1) {
                return i + 1;
            }
        }else if (cc==','){
            if(count==1){
                return i;
            }
        }
    }
    return (int) (strchr(line, ',') - line);
}

int parseData(char *line, int *pInt, int len) {
    int i, pos = 0;
    char numStr[10] = {0};
    for (i = 0; i < len; i++) {
        if (line[i] != '(')
            sprintf(numStr, "%s%c", numStr, line[i]);
        else {
            pos = i + 1;
            break;
        }
    }
    if (strcmp(numStr, "#") == 0) {
        *pInt = 0;
    } else {
        *pInt = atoi(numStr);
    }
    return pos;
}

大体如此,具体细节有待完善。后续可以考虑支持B+tree的广义表序列化反序列化。


你可能感兴趣的:(算法,二叉树)