[leetcode] Construct Binary Tree from Inorder and Postorder Traversal

Construct Binary Tree from Inorder and Postorder Traversal


class Solution {
public:
    TreeNode *buildTreebyIndex(vector<int> &inorder,int inBegin,int inEnd,vector<int> &postorder,int postBegin,int postEnd){
        if (inBegin>inEnd||postBegin>postEnd) {
            return nullptr;
        }
        int val=postorder[postEnd];
        int index;
        for (int i=inBegin; i<=inEnd; i++) {//注意条件为<=
            if (inorder[i]==val) {
                index=i;
                break;
            }
        }
        int len=index-inBegin;
        TreeNode *node=new TreeNode(val);
        
        TreeNode *pleft=buildTreebyIndex(inorder, inBegin, index-1, postorder, postBegin, postBegin+len-1);
        TreeNode *pright=buildTreebyIndex(inorder, index+1, inEnd, postorder, postBegin+len, postEnd-1);

        node->left=pleft;
        node->right=pright;
        
        return node;
        
    }
    
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        if (inorder.size()==0) {
            return nullptr;
        }
        return buildTreebyIndex(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
    }
};


你可能感兴趣的:([leetcode] Construct Binary Tree from Inorder and Postorder Traversal)