题解 | #从中序与后序遍历序列构造二叉树#

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

https://www.nowcoder.com/practice/ab8dde7f01f3440fbbb7993d2411a46b

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param inorder int整型vector 中序遍历序列
     * @param postorder int整型vector 后序遍历序列
     * @return TreeNode类
     */

    TreeNode* func(vector<int>& inorder,int inBegin,int inEnd,vector<int>& postorder,int postBegin,int postEnd){
        if(inBegin < 0 || inEnd >= inorder.size() || inBegin > inEnd){
            return NULL;
        }
        if(postBegin < 0 || postEnd >= postorder.size() || postBegin > postEnd){
            return NULL;
        }
        TreeNode* head = new TreeNode(postorder[postEnd]);
        int index;
        for(int i = inBegin;i<=inEnd;i++){
            if(inorder[i] == postorder[postEnd]){
                index = i;//根节点索引
            }
        }
        int leftsize = index - inBegin;
        head->left = func(inorder,inBegin,index-1,postorder,postBegin,postBegin+leftsize-1);
        head->right = func(inorder,index+1,inEnd,postorder,postBegin+leftsize,postEnd-1);
        return head;
    }

    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        // write code here
        if(inorder.size() == 0 || postorder.size() == 0){
            return {};
        }
        TreeNode* head = func(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
        return head;
    }
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务