zoukankan      html  css  js  c++  java
  • 算法之重建二叉树

    输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
    例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

     //m,n 前序数组的起点和终点 i,j 中序数组的起点和终点
    TreeNode * ConstructSub(vector<int>&preOrderVec,vector<int>&inOrderVec,int m,int n,int i,int j){
        int rootValue = preOrderVec[m];
        TreeNode * root = new TreeNode(rootValue);
        root->left=nullptr;
        root->right=nullptr;
    
        //边界, 左边或者右边只有一个元素的时候,并且前序和中序的值相等
        if(m==n && i==j){
            if(preOrderVec[m]==inOrderVec[i]){
                return root;
            }
            else{return nullptr;}
        }
    
    
        //找到左右两边
        //中序序列里的root的索引
        int rootInorderIndex=i;
        //往后开始找
        while (rootInorderIndex<n&&inOrderVec[rootInorderIndex]!=rootValue) {
            rootInorderIndex++;
        }
        //找到了,那就划分左右子树,然后递归
        int leftLength= rootInorderIndex-i;
        int leftPreorderEndIndex= m+leftLength;
        //存在左子树
        if(leftLength>0){
            root->left = ConstructSub(preOrderVec, inOrderVec, m+1, leftPreorderEndIndex,i,rootInorderIndex-1);
        }
        //存在右子树
        if(leftLength<n-m){
            root->right= ConstructSub(preOrderVec, inOrderVec, leftPreorderEndIndex+1, n, rootInorderIndex+1, j);
        }
        return root;
    }
  • 相关阅读:
    java实现二叉树的构建以及三种遍历
    binary-tree-preorder-traversal二叉树的前序遍历
    insertion-sort-list使用插入排序对链表进行排序
    binary-tree-postorder-traversa二叉树的后序遍历
    sort-list
    Redis的数据类型
    在Windows上搭建Redis服务器
    Eureka源码分析
    Eureka概念理解
    Spring Cloud Eureka
  • 原文地址:https://www.cnblogs.com/xiaonanxia/p/10522188.html
Copyright © 2011-2022 走看看