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

/**
 * 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 il,int ir,int postl,int postr) {//[)
        if(il==ir) return NULL;
        TreeNode* root=new TreeNode(postorder[postr-1]);
        int k=find(inorder.begin()+il,inorder.begin()+ir,postorder[postr-1])-inorder.begin();
        root->left=buildTree(inorder,postorder,il,k,postl,k-il+postl);
        root->right=buildTree(inorder,postorder,k+1,ir,k-il+postl,postr-1);
        return root;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        return buildTree(inorder,postorder,0,inorder.size(),0,postorder.size());
    }
};

你可能感兴趣的:(Leetcode 106. 从中序与后序遍历序列构造二叉树)