• 数据结构-重建二叉树


    #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;
    }
  • 相关阅读:
    我们需要测试!
    BlueStacks安装教程
    性能测试知多少系统架构分析
    免费去纽约 赢取总额20万美金 立即报名参加微软创新杯全球大学生大赛
    羡慕嫉妒别人只能说明自己不行
    算法和工程?那个重要......
    学习c++的优秀博客(更新ing)
    《启程》
    一点点反思
    提问的技巧
  • 原文地址:https://www.cnblogs.com/wn19910213/p/3706641.html
Copyright © 2020-2023  润新知