• 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;
    }
  • 相关阅读:
    LeetCode Best Time to Buy and Sell Stock
    LeetCode Scramble String
    LeetCode Search in Rotated Sorted Array II
    LeetCode Gas Station
    LeetCode Insertion Sort List
    LeetCode Maximal Rectangle
    Oracle procedure
    浏览器下载代码
    Shell check IP
    KVM- 存储池配置
  • 原文地址:https://www.cnblogs.com/zufezzt/p/4523251.html
Copyright © 2020-2023  润新知