已知前序遍历与中序遍历,重建二叉树

 由前序遍历和中序遍历即可确定一棵二叉树,前序遍历的第一个节点即为二叉树的根节点,则在中序遍历中可根据根节点的位置将中序遍历数组分为左子树部分和右子树部分,即可根据此性质采用递归的方法,依次确定二叉树的每一个节点,进而确定二叉树。

代码如下:

class Solution {
public:
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
      
        auto len1=pre.size();
        auto len2=vin.size();
        if(len1==0&&len2==0)
        {
            return nullptr;
        }
        return CreateTree(pre,vin,0,len1-1,0,len2-1);
    }
    
    TreeNode* CreateTree(vector<int> pre,vector<int> vin,int pStart,int pEnd,int vStart,int vEnd)
    {
        TreeNode *tree=new TreeNode(pre[pStart]);
        tree->left=nullptr;
        tree->right=nullptr;
        if(pStart==pEnd&&vStart==vEnd)
        {
            return tree;
        }
        int i=0;
        for(i=vStart;i<=vEnd;i++)//通过循环确定根节点在中序遍历中的位置
        {
            if(vin[i]==pre[pStart])
            {
                break;
            }
        }
        int leftLength=i-vStart;
        int rightLength=vEnd-i;
        //通过递归确定右子树和左子树中的每一个节点,直至叶子结点的孩子为空即返回二叉树
        if(leftLength>0)
        {
            tree->left=CreateTree(pre,vin,pStart+1,pStart+leftLength,vStart,i-1);
        }
        if(rightLength>0)
        {
            tree->right=CreateTree(pre,vin,pStart+leftLength+1,pEnd,i+1,vEnd);
        }
        return tree;
    }
};

猜你喜欢

转载自blog.csdn.net/zlb666/article/details/86483115
今日推荐