zoukankan      html  css  js  c++  java
  • 从中序后序遍历构造

    1.构造二叉树的必要条件
    必须需要中序遍历和一个前序或者中序遍历
    构造二叉树=前序+中序 =后序+中序
    2.那如何根据中序和后序遍历去构造二叉树呢?
    比如给出 inorder(中序)=[9,3,15,27]
    postorder(后序遍历)=[9,15,7,20,3]
    就可以构造出一个唯一的二叉树:

    那怎么做呢?采取分割法。
    以后序数组的最后一个元素作为分割点,你可以把它理解为当前树的中点,然后切开中
    序数组,划分成左右子树,直到后序数组只有一个元素

    使用递归算法处理

    TreeNode* build(vector<int>&inorder,vector<int>&postorder)
        {
            1.如果后序遍历为空,那么这是一个空树
            if(postorder.size()==0)return nullptr;
            2.选择后序遍历的最后一个元素最为分割点
            int rootVal=postorder[postorder.size()-1];
            TreeNode * root=new TreeNode(rootVal);
            3.如果这个时候后序数组只有1个元素,那么它是叶子节点
            if(postorder.size()==1)return root;
            4.在中序遍历的数组内部寻找割点
            int dimpoint;
            for(dimpoint=0;dimpoint<inorder.size();dimpoint++)
            {
                if(inorder[dimpoint]==rootVal){break;}
            }
            切割中序左数组,使用左闭右开原则
            vector<int> leftinorder(inorder.begin(),inorder.begin()+dimpoint);
            切割中序右数组
            vector<int> rightinorder(inorder.begin()+dimpoint+1,inorder.end());
            切割后序数组为左右数组
            postorder.resize(postorder.size()-1);
            vector<int> leftpostorder(postorder.begin(),postorder.begin()+leftinorder.size());;
            vector<int> rightpostorder(postorder.begin()+leftinorder.size(),postorder.end());
            
            root->left=build(leftinorder,leftpostorder);
            root->right=build(rightinorder,rightpostorder);
            return root;
        }
    

    但是,前序和中序无法唯一的确定一颗二叉树。

  • 相关阅读:
    Weblogic任意文件上传漏洞(CVE-2018-2894)复现
    Angular动态创建组件之Portals
    nodejs 开发企业微信第三方应用入门教程
    系列文章|OKR与敏捷(三):赋予团队自主权
    Angular开发技巧
    系列文章|OKR与敏捷(二):实现全栈敏捷
    系列文章|OKR与敏捷(一):瀑布式目标与敏捷的冲突
    OKR与Scrum如何强强联手
    Service Worker
    RxJS 实现摩斯密码(Morse) 【内附脑图】
  • 原文地址:https://www.cnblogs.com/cwllife/p/14671716.html
Copyright © 2011-2022 走看看