• 知道二叉树的先序和中序遍历,重建该二叉树


    #include <iostream>
    using namespace std;
    
    struct node{
        char data;
        node* lchild;
        node* rchild;
    };
    
    //给定一棵二叉树的先序遍历序列和中序遍历序列,重建这棵二叉树
    char pre[] = {'A', 'B', 'D', 'E', 'C', 'F'};  //先序遍历序列
    char in[]={'D', 'B', 'E', 'A', 'F', 'C'};   //中序遍历序列
    //当前先序序列区间为[preL, preR],中间序列区间为[inL, inR],返回根节点地址
    node* create(int preL, int preR, int inL, int inR){
        if(preL > preR){
            return NULL;  //先序序列长度小于等于0时,直接返回
        }
        node* root = new node;  //新建一个新节点,用来存放当前二叉树的根节点
        root->data = pre[preL];   //新节点的数据域为根节点的值
        int k;
        for(k = inL; k <= inR; k++){
            if(in[k] == pre[preL]){    //在中序序列中找到in[k] == pre[L]的结点
                break;
            }
        }
        int numLeft = k - inL;  //左子树的结点个数
    
        //左子树的先序区间为[preL+1, preL+numLeft],中序区间为[inL, k-1]
        //返回左子树的根节点地址,赋值给root的左指针
        root->lchild = create(preL+1, preL+numLeft, inL, k-1);
    
        //右子树的先序区间为[preL+numLeft+1, preR],中序区间为[k+1, inR]
        //返回右子树的根节点地址,赋值给root的右指针
        root->rchild = create(preL+numLeft+1, preR, k+1, inR);
        return root;
    }
    
    void preorder(node* root){  //先序遍历重建的树
        if(root == NULL){
            return;  //到达空树,递归边界
        }
        //访问根节点root,例如将其数据域输出
        printf("%c
    ", root->data);
        preorder(root->lchild);
        preorder(root->rchild);
    }
    int main() {
        node* root = new node;
        root = create(0,5,0,5);
        preorder(root);
    
        return 0;
    }
  • 相关阅读:
    七七四十九劫,九九八十一难
    Android中用layer-list编写阴影效果
    Android 高手进阶之自定义View,自定义属性(带进度的圆形进度条)
    Effective C++ 24,25
    windows系统port监听
    线程同步辅助类——Exchanger
    C/C++中constkeyword
    【COCOS2DX-游戏开发之三三】TMX边界控制与小窗体内预览TMX
    IDFA的值什么时候会发生改变
    hadoop(六)
  • 原文地址:https://www.cnblogs.com/dear_diary/p/8444371.html
Copyright © 2020-2023  润新知