• 数据结构-重建二叉树


    #include <iostream>
    
    using namespace std;
    
    struct BinaryTreeNode{
        int data;
        BinaryTreeNode* lchild;
        BinaryTreeNode* rchild;
    };
    
    BinaryTreeNode* Rebuilt(int *pre,int* preEnd,int* in,int* inEnd){
        BinaryTreeNode* root = new BinaryTreeNode;
        root->data = pre[0];
        root->lchild = root->rchild = NULL;
    
        if(pre == preEnd){    //循环结束条件
            return root;
        }
    
        int* curP = in;
        while(*curP != pre[0] && in < inEnd){   //寻找中序和先序相同的节点
            curP++;
        }
    
        int LchildSize = curP - in;
        int* LchildEnd = pre + LchildSize ;
    
        if(LchildSize > 0){
            root->lchild = Rebuilt(pre+1,pre+LchildSize,in,curP-1);     //控制左节点范围进行递归
        }
    
        if((preEnd - pre) > LchildSize){
            root->rchild = Rebuilt(pre+LchildSize+1,preEnd,curP+1,inEnd);
        }
    
        return root;
    }
    
    BinaryTreeNode* Start(int* pre,int* in,int size){
        if(pre == NULL || in == NULL){
            return NULL;
        }
    
        return Rebuilt(pre,pre+size-1,in,in+size-1);   //控制左右子节点的范围
    }
    
    void PreOrder(BinaryTreeNode* root){
        if(root != NULL){
            cout << root->data << " ";
            PreOrder(root->lchild);
            PreOrder(root->rchild);
        }
    }
    
    void InOrder(BinaryTreeNode* root){
        if(root != NULL){
            InOrder(root->lchild);
            cout << root->data << " ";
            InOrder(root->rchild);
        }
    }
    
    void PostOrder(BinaryTreeNode* root){
        if(root != NULL){
            PostOrder(root->lchild);
            PostOrder(root->rchild);
            cout << root->data << " ";
        }
    }
    
    int main()
    {
        int Pre[] = {1,2,4,7,3,5,6,8};
        int In[] = {4,7,2,1,5,3,8,6};
        int Size = sizeof(Pre)/sizeof(int);   //获取长度,以便得到尾指针
    
        BinaryTreeNode *root = Start(Pre,In,Size);
    
        cout << "先序遍历: " ;
        PreOrder(root);
        cout << endl;
        cout << "中序遍历: " ;
        InOrder(root);
        cout << endl;
        cout << "后序遍历: " ;
        PostOrder(root);
        return 0;
    }
  • 相关阅读:
    Java 中日常使用的 IO 流总结
    NIO 实现非阻塞 Socket 通讯
    Java NIO 的简单介绍和使用
    常用设计模式 -- 一分钟就能学会的门面模式(外观模式)
    Java日志框架介绍和 Slf4j 使用
    Linux学习一
    JavaScript-数组
    javascript
    idea 快捷键汇总
    正则表达式
  • 原文地址:https://www.cnblogs.com/wn19910213/p/3706641.html
Copyright © 2020-2023  润新知