Post-order traversal of complete binary tree output level traversal (recursive tree creation/dfs simulation/tabulation)

Idea: A very critical condition is that the size of the tree can be determined and placed in order one by one.

Recall that the binary tree is determined by the middle-order traversal and the post-order traversal. Every time we find the next smaller interval of the left and right subtrees to recurse.

Then this idea continues. According to the complete binary tree, the empty tree is recursively established first, and the siz of each node subtree is pushed_up during the establishment process.

Then recursively find the subtree in the input array, and finally output it with bfs.


It feels that the chair tree of the line segment tree has been stunned recently, and it will be used when it comes up. But if you go to the simulation, you will know that the line segment tree and this tree are completely corresponding only when the tree is full, otherwise the corresponding state of the tree built is different.

Because the line segment tree is divided by intervals, and the trees in these classes are divided by nodes. 

Note: The boundary of recursion in the code is calculated using the current of the left subtree. (I adjusted this bug for a long time

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=1e5;
typedef int LL;
LL n;
struct Tree{
    LL lson,rson;
    LL val;
    LL siz;
}tree[maxn*4];
LL a[maxn];
LL build(LL p){///先建好对应的空树
    if(p>n) {
        tree[p].siz=0;
        return -1;
    }
    tree[p].siz=1;
    tree[p].val=-1;
    tree[p].lson=build(p*2);
    tree[p].rson=build(p*2+1);
    tree[p].siz=tree[p*2].siz+tree[p*2+1].siz+1;
    return p;
}
void update(LL p,LL l,LL r){
    if(p>n) return;
    tree[p].val=a[r];

    update(p*2,l,l+tree[p*2].siz-1);
    update(p*2+1,l+tree[p*2].siz,r-1);
}
void bfs(){
    queue<LL>que;
    que.push(1);///树根节点
    while(!que.empty()){
        LL p=que.front();que.pop();

        if(p>n) break;
        que.push(p*2);
        que.push(p*2+1);
    }
}
int main(void)
{
  cin.tie(0);std::ios::sync_with_stdio(false);
  cin>>n;
  LL root=build(1);
  for(LL i=1;i<=n;i++) cin>>a[i];

  update(root,1,n);
  bfs();
return 0;
}

 


Provide some other practices:

Wang Ge manually typed the table, that is, manually determined the depth shape of the tree corresponding to each n, and then typed the table for output. 

dfs directly save the node.

%%%zx poly (zx poly is too strong

 

Guess you like

Origin blog.csdn.net/zstuyyyyccccbbbb/article/details/110312659