LeetCode从前序与中序遍历序列构造二叉树,从中序与后序遍历序列构造二叉树

Posted zhaocx111222333

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode从前序与中序遍历序列构造二叉树,从中序与后序遍历序列构造二叉树相关的知识,希望对你有一定的参考价值。

从前序与中序遍历序列构造二叉树

在这里插入图片描述

采用递归创建:
1.对于参数preorder,采用引用的方式创建,保证共用一个
2.startidx和endidx直接传数字,每一层递归都有自己的值
3.递归的结束条件是<而不是<=,因为start和end指向同一个元素时,这个元素还没有创建,在接下来创建他的子树才会返回
4.每一层递归要创建preorder[preidx]为值的数,然后创建他们的左子树,右子树(因为前序遍历的顺序是根左右,先左后右,而下个题后序遍历就是左右跟,而我们是反向遍历,所以先遍历右子树。)

class Solution {
public:
    TreeNode* _buildTree(vector<int>& preorder, vector<int>& inorder,
    int& preidx,int startidx,int endidx){
        //递归的结束条件就是中序的里面没有元素
        if(startidx>endidx){return nullptr;}
        //创建根
        TreeNode* cur=new TreeNode(preorder[preidx]);
        int curidx=startidx;
        for(;curidx<=endidx;++curidx){
            if(inorder[curidx]==preorder[preidx])
                break;
        }
        //创建根的左右子树
        //左子树区间
        if(startidx<curidx)
            cur->left=_buildTree(preorder,inorder,++preidx,startidx,curidx-1);
            //注意不能写--,要写-1
        else
            cur->left=nullptr;
        //右
        if(curidx<endidx)
            cur->right=_buildTree(preorder,inorder,++preidx,curidx+1,endidx);
        else
            cur->right=nullptr;
        return cur;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int preidx=0;
        return _buildTree(preorder,inorder,preidx,0,inorder.size()-1);

    }
};

从中序与后序遍历序列构造二叉树

后序遍历仅仅改了前序的索引位置和左右创建的顺序

class Solution {
public:
TreeNode* _buildTree(vector<int>& postorder, vector<int>& inorder,
    int& postidx,int startidx,int endidx){
        //递归的结束条件就是中序的里面没有元素
        if(startidx>endidx){return nullptr;}
        //创建根
        TreeNode* cur=new TreeNode(postorder[postidx]);
        int curidx=startidx;
        for(;curidx<=endidx;++curidx){
            if(inorder[curidx]==postorder[postidx])
                break;
        }
        //创建根的左右子树
        //右
        if(curidx<endidx)
            cur->right=_buildTree(postorder,inorder,--postidx,curidx+1,endidx);
        else
            cur->right=nullptr;
            //左子树区间
        if(startidx<curidx)
            cur->left=_buildTree(postorder,inorder,--postidx,startidx,curidx-1);
            //注意不能写--,要写-1
        else
            cur->left=nullptr;
        return cur;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int postidx=inorder.size()-1;
        return _buildTree(postorder,inorder,postidx,0,inorder.size()-1);

    }
};

非递归

在这里插入图片描述在这里插入图片描述

以上是关于LeetCode从前序与中序遍历序列构造二叉树,从中序与后序遍历序列构造二叉树的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 105. 从前序与中序遍历序列构造二叉树

LeetCode105. 从前序与中序遍历序列构造二叉树

leetcode: 105. 从前序与中序遍历序列构造二叉树

leetcode 105. 从前序与中序遍历序列构造二叉树

LeetCode105. 从前序与中序遍历序列构造二叉树

LeetCode 105. 从前序与中序遍历序列构造二叉树