树的遍历

一:由先序和中序,确定后序

post(0,0,n-1);
void toPost(int root,int left,int right){//root为先序中根节点的下标,left和right分别为中序中子树的左右边界
    if(left>right){
        return ;
    }
    int i=left;
    while(i<right&&mid[i]!=pre[root]){
        i++;
    }
    toPost(root+1,left,i-1);//递归结束后,root到达左子树的左边叶子结点
    toPost(root+1+i-left,i+1,right);//递归结束后,root到达右子树的右边叶子结点
    post.push_back(pre[root]);
    
}

 

二:由后序和中序,确定先序

pre(n-1,0,n-1);
void toPre(int root,int left,int right){
    if(left>right){
        return ;
    }
    int i=left;
    while(i<right&&mid[i]==post[root]){
        i++;
    }
    toPre(root+1-right+i,left,i-1);
    toPre(root-1,i+1,right);
    pre.push_back(post[root]);
}

 

posted @ 2021-02-23 20:49  XA科研  阅读(47)  评论(0编辑  收藏  举报