用括号法递归建立二叉树

描述
如果用大写字母标识二叉树节点,则一棵二叉树可以用以下字母序列建立,#表示空节点。试写一个递归算法,有这种形式的字符序列,建立相应的二叉树的二叉链表存储结构,并按层次遍历输出。如一棵二叉树可表示为:A(B(#,D),C(E(#,F),#))
 
输入
按题中要求,用括号法输入二叉树序列,#表示空节点
 
输出
按层次遍历建立好的二叉树并输出
 
输入样例
A(B(#,D),C(E(#,F),#))
 
输出样例

ABCDEF

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include <iostream>
#include <queue>

using namespace std;

typedef struct BinTreeNode{
    char data;
    struct BinTreeNode *lchild;
    struct BinTreeNode *rchild;
}BinTreeNode,*BinTree;

int FindComma(char s[], int len)
{
    int match = 0;
    int i;
    for(i = 0; i < len; i++)
    {
        if(s[i] == '(')
            ++match;
        else if(s[i] == ')')
            --match;
        if(match==0 && s[i]==',')
            break;
    }
    return i;
}
BinTree Create(char s[], int len)
{
    if(s[0] == '#')
        return NULL;
    BinTree root = (BinTree)malloc(sizeof(BinTreeNode));
    root->data = s[0];
    if(len == 1)
    {
        root->lchild = NULL;
        root->rchild = NULL;
    }
    else
    {
        int commaPos = FindComma(s+2, len-2);
        root->lchild = Create(s+2, commaPos);
        root->rchild = Create(s+2+commaPos+1,len-3-commaPos-1);
    }
    return root;
}
void LevelPrint(BinTree T)
{
    queue<BinTree>q;
    if(T==NULL)return;
    BinTree p = T;
    q.push(p);
    while(!q.empty())
    {
        p = q.front();
        q.pop();
        if(p->data != '#')
            printf("%c",p->data);
        if(p->lchild)
            q.push(p->lchild);
        if(p->rchild)
            q.push(p->rchild);
    }
    printf("\n");
}
int main()
{
    char str[200];
    scanf("%s",&str);
    BinTree root;
    root = (BinTree)malloc(sizeof(BinTreeNode));
    root = Create(str, strlen(str));
    LevelPrint(root);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zhao2018/article/details/80754319
今日推荐