zoukankan      html  css  js  c++  java
  • BUAA 2014级数据结构第五次上机 二叉树之数组转换广义表

    按题意建立好二叉树,再按照先序遍历输出结果。

    #include<cstdio>
    #include<vector>
    #include<queue>
    #include<string.h>
    #include<algorithm>
    using namespace std;
    
    struct node
    {
        int left, right, date;
    
    }node[1005];
    
    int a[1005], flag[1005];
    
    void dfs(int father)
    {
        printf("%d", node[father].date);
        if (node[father].left != -1 || node[father].right != -1) printf("(");
        if (node[father].left != -1 && node[father].right == -1)
        {
            dfs(node[father].left);
            printf(")");
        }
        else if (node[father].left == -1 && node[father].right != -1)
        {
            printf(",");
            dfs(node[father].right);
            printf(")");
        }
        else if (node[father].left != -1 && node[father].right != -1)
        {
            dfs(node[father].left);
            printf(",");
            dfs(node[father].right);
            printf(")");
        }
        
    }
    
    int main()
    {
        int n, i;
        while (~scanf("%d", &n))
        {
            int numm = 1;
            for (i = 0; i <= 1000; i++)
            {
                node[i].date = -1;
                node[i].left = -1;
                node[i].right = -1;
            }
            memset(flag, 0, sizeof(flag));
            for (i = 1; i <= n; i++) scanf("%d", &a[i]);
            int father = 1, jishu = 0;
            node[numm].date = a[1]; numm++;
            for (i = 2; i <= n; i++)
            {
                if (jishu == 0)
                {
                    jishu++;
                    if (a[i] != -1)
                    {
                        node[father].left = numm;
                        node[numm].date = a[i];
                        numm++;
                    }
                }
                else if (jishu == 1)
                {
                    if (a[i] != -1)
                    {
                        node[father].right = numm;
                        node[numm].date = a[i];
                        numm++;
                    }
                    jishu = 0;
                    father++;
                }
            }
            dfs(1);
            printf("
    ");
        }
        return 0;
    }
  • 相关阅读:
    外设简述
    代C语言上机实践
    css动画效果
    css滑动门原理
    css整理
    html
    html单词
    倒计时.js
    随机方块
    求字符串出现次数和最大值
  • 原文地址:https://www.cnblogs.com/zufezzt/p/4523251.html
Copyright © 2011-2022 走看看