zoukankan      html  css  js  c++  java
  • 根据二叉树的先序遍历和中序遍历建立二叉树

    学过数据结构的应该都知道,根据先序遍历和中序遍历可以唯一确定一颗二叉树,二叉树是递归定义的数据结构,所以一般的操作都是递归完成的,所以建树的过程也不例外,先来看这样两道题

    题目一 :http://acm.hnust.cn/JudgeOnline/problem.php?id=1047

    题目二 :http://acm.hnust.cn/JudgeOnline/problem.php?id=1802

    其实这两道题的本质都是通过先序遍历和中序遍历建立一颗二叉树,比方说ABCD 和 BCAD这一组数据, 先序遍历的第一个字符是A,说明他是整棵树的根,以A为中心又将中序遍历序列分为了两部分,也就是根节点的左右子树,而根据中序遍历又可以把先序遍历序列再分为两部分,通过这两部分又可以确定左右子树的根,根据左右子树的根又可以确定左右子树的左右子树,这样递归下去直到序列中只剩下一个字符时就是叶子节点,这两道题都可以选择"建树"或者“不建树”直接根据序列一气呵成

    题目二“建树”代码

    #pragma GCC diagnostic error "-std=c++11"
    #include <bits/stdc++.h>
    #define _ ios_base::sync_with_stdio(0);cin.tie(0);
    
    using namespace std;
    const int N = 26 + 5;
    
    struct node{
        char data;
        int lchild, rchild;
        node(){ lchild = rchild = 0; }
    }Tree[N];
    
    int newnode(int x = 0){
        static int sz = 1;
        if(x) sz = 1;
        return sz++;
    }
    
    char pre[N], in[N];
    
    void DFS(int & rt, int ps, int pt, int is, int it){
        if(rt == 0) rt = newnode();
        int pos = is;
        Tree[rt].data = pre[ps]; //根节点数据域赋值
        while(in[pos] != pre[ps]) pos++;
        if(pos != is){ //左子树不为空递归创建左子树
            DFS(Tree[rt].lchild, ps + 1, ps + pos - is, is, pos -1);
        }
        if(pos != it){ //右子树不为空递归创建右子树
            DFS(Tree[rt].rchild, ps + 1 + pos - is, pt, pos + 1, it);
        }
    }
    
    void Post_Order(int rt){
        if(rt == 0) return;
        Post_Order(Tree[rt].lchild);
        Post_Order(Tree[rt].rchild);
        printf("%c", Tree[rt].data);
        Tree[rt].lchild = Tree[rt].rchild = 0; //递归结束,左右子树清空
    }
    
    int main(){
        while(scanf("%s %s", pre, in) == 2){
            int root = 0;
            DFS(root, 0, strlen(pre) - 1, 0, strlen(in) - 1);
            Post_Order(root); puts("");
            newnode(true);
        }
        return 0;
    }

    题目二“不建树”代码

    #pragma GCC diagnostic error "-std=c++11"
    #include <bits/stdc++.h>
    #define _ ios_base::sync_with_stdio(0);cin.tie(0);
    
    using namespace std;
    const int N = 26 + 5;
    
    char pre[N], in[N];
    void DFS(int ps, int pt, int is, int it){
        int pos = is;
        while(in[pos] != pre[ps]) pos++;
        if(pos != is){
            DFS(ps + 1, ps + pos - is, is, pos - 1);
        }
        if(pos != it){
            DFS(ps + 1 + pos - is, pt, pos + 1, it);
        }
        printf("%c", pre[ps]);
    }
    int main(){
        while(scanf("%s %s", pre, in) == 2){
            DFS(0, strlen(pre) - 1, 0, strlen(in) - 1);
            printf("
    ");
        }
        return 0;
    }
  • 相关阅读:
    binder机制理解
    Android 资源目录
    Andriod 构建项目流程
    dpi、ppi 、dp、sp、px、 pt相关概念
    短语、直接短语和句柄
    MySql优化
    java虚拟机内存管理
    redis
    linux——nginx的安装及配置
    linux——高级文本处理命令之wc、cut、sort
  • 原文地址:https://www.cnblogs.com/Pretty9/p/7426958.html
Copyright © 2011-2022 走看看