zoukankan      html  css  js  c++  java
  • PAT(Advanced Level)A1020. Tree Traversals

    题意

    给后序序列和前序序列,要求求出这个二叉树的层序遍历

    思路

    • 关键在于根据后序序列和前序序列定出二叉树。

      • 二叉树是递归定义的,所以根据后序序列和中序序列定树同样是递归式的
      • 1⃣️每次都先在中序序列中找到根root,通过后序序列我们可以快速得知当前的root(后序序列最后一个)
      • 2⃣️统计出右子树结点的个数(统计左子树的也可以)
      • 3⃣️递归处理左子树,右子树
      • 递归的边界是看区间长度,左>右就退出
      			    1
      			   / 
      			  2   3
      			 /  / 
      			4  5 6  7
      
      index:       0 1 2 3 4 5 6
      postorder:   4 5 2 6 7 3 1
      inoder:      4 2 5 1 6 3 7
      
    • 层序遍历:其实和普通的BFS没什么区别,主要是层序遍历,所以每次我们都是出一层长度的结点并进行扩充。没有什么难度

    代码

    #include <algorithm>
    #include <cstdio>
    #include <cstring>
    #include <iostream>
    #include <vector>
    #include <queue>
    using namespace std;
    int post_order[50], in_order[50];
    int N;
    vector<int> ans;
    struct Node
    {
        int val;
        Node* lchild;
        Node* rchild;
    };
    Node* Create(int postL, int postR, int inL, int inR)
    {
        if(postL > postR)
            return NULL;
        Node* root = new Node;
        root->val = post_order[postR];
        int pos;
        for(pos=inL;pos<=inR;pos++)
        {
            if(in_order[pos] == root->val)
                break;
        }
        int numRight = inR - pos;   //右子树的区间长度
        root->rchild = Create(postR - numRight, postR - 1, pos + 1, inR);
        root->lchild = Create(postL, postR - numRight - 1, inL, pos - 1);
        return root;
    }
    void Level_order(Node* root)
    {
        queue<Node*> q;
        q.push(root);
        while(!q.empty())
        {
            int size = q.size();
            for(int i=0;i<size;i++)
            {
                auto cur = q.front();
                q.pop();
                ans.emplace_back(cur->val);
                if(cur->lchild)
                {
                    q.push(cur->lchild);
                }
                if(cur->rchild)
                {
                    q.push(cur->rchild);
                }
            }
        }
    }
    int main()
    {
        cin >> N;
        for(int i=0;i<N;i++)
            cin >> post_order[i];
        for(int i=0;i<N;i++)
            cin >> in_order[i];
        Node* root = Create(0, N-1, 0, N-1);
        Level_order(root);
        for(int i=0;i<ans.size();i++)
            i == ans.size() - 1 ? cout << ans[i] : cout << ans[i] << " ";
        return 0;
    }
    
  • 相关阅读:
    HTC G12 HBOOT 2.0.0002 官解、降级精简教程!
    android call require api level
    刷机流程
    Android通过tcpdump抓包
    [原创]c#的线性表 Virus
    [原创]c++线性表的插入 Virus
    [原创]关于编程论坛封我ID的意见 Virus
    [原创]文件管理 Virus
    [原创]c#高级编程学习笔记(连载_委托) Virus
    [原创]c#中的内存管理 Virus
  • 原文地址:https://www.cnblogs.com/MartinLwx/p/13748989.html
Copyright © 2011-2022 走看看