二叉树递归/层序创建,递归/非递归三种遍历

BinTree CreatBinTree()
{
    BinTree T = (BinTree)malloc(sizeof(struct TNode));
    char ch;
    ch = getchar();
    if(ch == '*')
        T = NULL;
    else{
        T->Data = ch;   //先序递归创建二叉树
        T->Left = CreatBinTree();
        T->Right = CreatBinTree();
    }
    return T;
}

BinTree CreatBinTree()//利用队列层序创建二叉树
{
    BinTree BT,T;
    char ch;
    Queue Q = CreatQueue();

    ch = getchar();
    if(ch != '*'){
        BT = (BinTree)malloc(sizeof(struct TNode));
        BT->Data = ch;
        BT->Left = BT->Right = NULL;
        AddQ(Q,BT);
    }
    else
        return NULL;

    while(!IsEmpty(Q)){
        T = Delete(Q);
        ch = getchar();
        if(ch == '*')
            T->Left = NULL;
        else{
            T->Left = (BinTree)malloc(sizeof(struct TNode));
            T->Left->Data = ch;
            T->Left->Left = T->Left->Right = NULL;
            AddQ(Q, T->Left);
        }
        
        ch = getchar();
        if(ch == '*')
            T->Right == NULL;
        else{
            T->Right = (BinTree)malloc(sizeof(struct TNode));
            T->Right->Data = ch;
            T->Right->Left = T->Right->Right = NULL;
            AddQ(Q,T->Right);
        }
    }
    return BT;
}

猜你喜欢

转载自blog.csdn.net/weixin_44061561/article/details/85162413