A1110 Complete Binary Tree (25 分| 完全二叉树,附详细注释,逻辑分析)

写在前面

  • 思路分析
    • 给出1个n表示有n个结点,这n个结点为0~n-1,给出这n个结点的左右孩子,求问这棵树是不是完全二叉树
      • 递归出最大的下标值,完全二叉树1定把前面下标充满:
        • 最大下标值 == 最大节点数
        • 不完全二叉树前满1定有位置是空,会往后挤
          • 最大下标值 > 最大节点数
  • 知识盲点,学习ing
    • 思想值得学习研究

测试用例

  • input:
    9
    7 8
    - -
    - -
    - -
    0 1
    2 3
    4 5
    - -
    - -
    output:
    YES 8
    
    intput:
    8
    - -
    4 5
    0 6
    - -
    2 3
    - 7
    - -
    - -
    output:
    NO 1
    

ac代码

  • #include <iostream>
    using namespace std;
    struct node
    {
        int l, r;
    } a[100];
    int maxn = -1, ans;
    void dfs(int root, int inx)
    {
        if(inx > maxn)
        {
            // 记录节点数
            maxn = inx;
            // 记录最后节点
            ans = root;
        }
    
        // 遍历左子树
        if(a[root].l != -1) dfs(a[root].l, inx*2);
        // 遍历右子树
        if(a[root].r != -1) dfs(a[root].r, inx*2+1);
    }
    
    int main()
    {
        int n, root = 0, have[100] = {0};
        cin >> n;
        for(int i=0; i<n; i++)
        {
            // i为当前结点编号
            string l, r;
            cin >> l >> r;
            if(l == "-")
                a[i].l = -1;
            else
            {
                a[i].l = stoi(l);
                have[stoi(l)] = 1;
            }
            if (r == "-")
                a[i].r = -1;
            else
            {
                a[i].r = stoi(r);
                have[stoi(r)] = 1;
            }
        }
    
        // 找到跟结点,不一定从数组起点开始
        while(have[root] != 0) root++;
        dfs(root, 1);
        maxn == n ? printf("YES %d",ans) : printf("NO %d",root);
    
        return 0;
    }
    
发布了328 篇原创文章 · 获赞 107 · 访问量 39万+

猜你喜欢

转载自blog.csdn.net/qq_24452475/article/details/100598303