LeetCode 刷题系列 -- 106. 从中序与后序遍历序列构造二叉树

给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。

示例 1:


输入:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
输出:[3,9,20,null,null,15,7]
示例 2:

输入:inorder = [-1], postorder = [-1]
输出:[-1]

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal
 

思路:东哥带你刷二叉树(构造篇) :: labuladong的算法小抄

c++:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTree(vector& inorder, vector& postorder) {

        return buildTree(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1);
    }

    TreeNode* buildTree(vector& inorder, int inStart, int inEnd, vector& postorder, int posStart, int posEnd) {
        if(inStart>inEnd || posStart>posEnd) {
            return nullptr;
        }

        int rootVal = postorder[posEnd];
        cout<< rootVal << endl;
        int inIndex = inStart;
        for(int i=inStart;i<=inEnd;i++) {
            if(inorder[i] == rootVal) {
                inIndex = i;
                break;
            }
        }

        // 以 postorder[posEnd] 为根节点的左子树节点的个数
        int leftSize = inIndex - inStart;

        // 以 postorder[posEnd] 为根节点的左子树节点的个数
        int rightSize = inEnd - inIndex;


        TreeNode* root = new TreeNode(rootVal);
        root->left = buildTree(inorder,inStart,inIndex-1,postorder,posStart,posStart+leftSize-1);
        root->right = buildTree(inorder,inIndex+1,inEnd,postorder,posEnd-rightSize,posEnd-1);

        return root;
    }

};

你可能感兴趣的:(二叉树,LeetCode,leetcode,算法,职场和发展)