SDUTOJ 3346 - 数据结构实验之二叉树七:叶子问题

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_43545471/article/details/102657398

Problem Description

已知一个按先序输入的字符序列,如abd,eg,cf,(其中,表示空结点)。请建立该二叉树并按从上到下从左到右的顺序输出该二叉树的所有叶子结点。

Input

输入数据有多行,每一行是一个长度小于50个字符的字符串。

Output

按从上到下从左到右的顺序输出二叉树的叶子结点。

Sample Input

abd,eg,cf,
xnl,i,u,
Sample Output
dfg
uli

Hint

Source

xam

思路:
在层序遍历的基础上,判断该结点是不是叶子就可以了

层序遍历代码及思路

#include <stdio.h>
#include <string.h>

#define MaxTree 10

int i;

typedef struct Node
{
    char data;
    struct Node* lchild;
    struct Node* rchild;
} TreeNode;

TreeNode* create_tree(TreeNode* t, char str[])
{
    char ch = str[i++];
    if (ch == ',')
    {
        return NULL;
    }
    else
    {
        t = (TreeNode*)malloc(sizeof(TreeNode));
        t->data = ch;
        t->lchild = create_tree(t->lchild, str);
        t->rchild = create_tree(t->rchild, str);
    }
    return t;
}

void Travel(TreeNode* t)
{
    TreeNode *temp[55];
    int front = 0, rear = 0;
    temp[rear++] = t;
    while(rear > front)
    {
        if (temp[front])
        {
            if (temp[front]->lchild == NULL&&temp[front]->rchild == NULL)
            {
                printf("%c", temp[front]->data);
            }
            temp[rear++] = temp[front]->lchild;
            temp[rear++] = temp[front]->rchild;
        }
        front++;
    }
}

int main()
{
    TreeNode* root;
    char str[55];
    while(gets(str))
    {
        i = 0;
        root = create_tree(root, str);
        Travel(root);
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43545471/article/details/102657398