根据中序和后序序列重建二叉树 Construct Binary Tree from Inorder and Postorder Traversal

问题:Given inorder and postorder traversal of a tree, construct the binary tree.

参考:根据前序序列和中序序列重建二叉树,http://blog.csdn.net/ojshilu/article/details/11855167,两个问题如出一辙。

注意:下面程序并没有做严格的合法性检查。

1、递归时两个序列长度总是相等。

2、后序序列中的根节点必须在中序序列中能找到。

代码:

class Solution {
public:
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        int n = inorder.size();
        if(n == 0)
            return NULL;
        return construct(inorder, postorder, 0, n-1, 0, n-1);
    }
    
    TreeNode* construct(vector<int> &inorder, vector<int> &postorder, int inleft, int inright, int postleft, int postright)
    {
        TreeNode *root = new TreeNode(postorder[postright]);
        root->left = root->right = NULL;
        
        int i;
        for(i = inleft;i<=inright;i++)
        {
            if(inorder[i] == postorder[postright])
                break;
        }
        
        if(i > inleft)
            root->left = construct(inorder, postorder, inleft, i-1, postleft, postleft+i-inleft-1);
        if(i < inright)
            root->right = construct(inorder, postorder, i+1, inright, postleft+i-inleft, postright-1);
        
        return root;
    }
};


你可能感兴趣的:(根据中序和后序序列重建二叉树 Construct Binary Tree from Inorder and Postorder Traversal)