欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 106. 从中序与后序遍历序列构造二叉树(二叉树基础之树的重建)

程序员文章站 2022-05-20 20:25:12
...

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

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int n = inorder.size();
        return create(0,n-1,0,n-1,inorder,postorder);
    }
    TreeNode* create(int postL,int postR,int inL,int inR,vector<int>& inorder, vector<int>& postorder){
        if(postL>postR){
            return nullptr;
        }
        TreeNode* root = new TreeNode(postorder[postR]); 
        int idx = 0;
        for(int i = inL;i<=inR;i++){
            if(inorder[i]==postorder[postR]){
                idx = i;
                break;
            }
        }
        int numLeft = idx-inL;
        root->left = create(postL,postL+numLeft-1,inL,idx-1,inorder,postorder);
        root->right = create(postL+numLeft,postR-1,idx+1,inR,inorder,postorder);
        return root;
    }
};