zoukankan      html  css  js  c++  java
  • 1099 Build A Binary Search Tree (30 分)

    水~,和1064 Complete Binary Search Tree (30 分)类似。

    题意

    二叉树有N个结点(结点编号为0 ~ N-1),给出每个结点的左右孩子结点的编号(不存在用-1表示)。接着给出一个N个整数的序列,需要把这N个整数填入二叉树的结点中,使得二叉树成为一棵二叉查找树。输出这棵二叉查找树的层序遍历序列。

    思路

    对一棵二叉查找树来说,中序遍历序列是递增的,因此只需要把给定的整数序列从小到大排序,然后对给定的二叉树进行中序遍历,将排序后序列的整数按中序遍历的顺序填入二叉树,就可以形成二叉查找树。

    注意点

    由于根结点默认为0号结点,因此不需要寻找根结点。

    const int N=110;
    struct Node
    {
        int data;
        int lchild,rchild;
    }tree[N];
    int a[N];
    int n;
    int k;
    
    void inorder(int root)
    {
        if(root == -1) return;
    
        inorder(tree[root].lchild);
        tree[root].data=a[k++];
        inorder(tree[root].rchild);
    }
    
    void bfs(int root)
    {
        queue<int> q;
        q.push(root);
    
        int cnt=0;
        while(q.size())
        {
            int t=q.front();
            q.pop();
    
            cout<<tree[t].data;
            cnt++;
            if(cnt < n) cout<<' ';
    
            if(~tree[t].lchild) q.push(tree[t].lchild);
            if(~tree[t].rchild) q.push(tree[t].rchild);
        }
    }
    
    int main()
    {
        cin>>n;
    
        for(int i=0;i<n;i++)
            cin>>tree[i].lchild>>tree[i].rchild;
    
        for(int i=0;i<n;i++) cin>>a[i];
    
        sort(a,a+n);
    
        int root=0;
        inorder(root);
    
        bfs(root);
        //system("pause");
        return 0;
    }
    
  • 相关阅读:
    【设计模式】——抽象工厂模式
    【设计模式】——观察者模式
    Candy
    Two Sum
    Interleaving String
    Longest Valid Parentheses
    【设计模式】——建造者模式
    【设计模式】——外观模式
    Simplify Path
    Word Search
  • 原文地址:https://www.cnblogs.com/fxh0707/p/14455087.html
Copyright © 2011-2022 走看看