A1099 Build A Binary Search Tree (30 分| 二叉查找树,附详细注释,逻辑分析)

写在前面

  • 思路分析
    • 二叉搜索树 中序从小到大顺序输出
    • 从小到大可以建立一个树
  • 热点知识,学习ing

测试用例

  • input:
    9
    1 6
    2 3
    -1 -1
    -1 4
    5 -1
    -1 -1
    7 -1
    -1 8
    -1 -1
    73 45 11 58 82 25 67 38 42
    output:
    58 25 82 11 38 67 45 73 42
    

ac代码

  • 参考代码
    #include<iostream>
    #include<queue>
    #include<algorithm>
    using namespace std;
    struct Node
    {
       int data;
       int left,right;
    } root[105];
    int digit[105],now = 0;
    
    //中序建立二叉搜索树
    void Inorder(int x)
    {
       if(root[x].left != -1)
           Inorder(root[x].left);
       root[x].data = digit[now++];
       if(root[x].right != -1)
           Inorder(root[x].right);
    }
    
    int main()
    {
       int n,x,y;
       scanf("%d",&n);
       for(int i = 0; i < n ; i++ )
           scanf("%d%d",&root[i].left,&root[i].right);
       for(int i = 0 ; i < n; i++)
           scanf("%d",&digit[i]);
       sort(digit,digit+n);
       Inorder(0);
    
       // 层序遍历
       queue<Node>qu;
       qu.push(root[0]);
       vector<int>vec;
       while(qu.empty() == 0)
       {
           Node tmp = qu.front();
           qu.pop();
           vec.push_back(tmp.data);
           if(tmp.left != -1)
               qu.push(root[tmp.left]);
           if(tmp.right != -1)
               qu.push(root[tmp.right]);
       }
       for(int i = 0 ; i < n; i++)
           printf("%d%c",vec[i]," \n"[i==n-1]);
       return 0;
    }
    
发布了328 篇原创文章 · 获赞 107 · 访问量 39万+

猜你喜欢

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