首页 > 代码库 > Construct Binary Tree from Inorder and Postorder Traversal

Construct Binary Tree from Inorder and Postorder Traversal

方法和依据前序和中序遍历确定二叉树一致。

/**
 * 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) {
        return buildTree(postorder.begin(), postorder.end(), inorder.begin(), inorder.end());
    }
    
    typedef vector<int>::iterator Iterator;
    TreeNode *buildTree(Iterator postfirst, Iterator postlast, Iterator infirst, Iterator inlast)
    {
        if(postfirst == postlast)
            return nullptr;
        if(infirst == inlast)
            return nullptr;
        
        Iterator iter = find(infirst, inlast, *(postlast-1));
        int dis = distance(infirst, iter);
        
        TreeNode *res = new TreeNode(*(postlast-1));
        
        res->left = buildTree(postfirst, postfirst+dis, infirst, iter);
        res->right = buildTree(postfirst+dis, postlast-1, iter+1, inlast);
        
        return res;
    }
};

 

Construct Binary Tree from Inorder and Postorder Traversal