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

Construct Binary Tree from Inorder and Postorder Traversal

Construct Binary Tree from Inorder and Postorder Traversal

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

根据后序遍历和中序遍历构建一棵二叉树

/**
 * 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:
    void Build(int l1, int r1, int l2, int r2, const vector<int>& post, const vector<int> & in, TreeNode*& root){
        int i;
        for ( i = l2; i <= r2; i++)
        {
            if (in[i] == post[r1])
                break;
        }
        root = new TreeNode(post[r1]);
        if (i == l2)
            root->left = NULL;
        else
            Build(l1, l1 + i - l2 - 1, l2, i - 1,post, in,root->left); //边界条件
        if (i == r2)
            root->right = NULL;
        else
            Build(l1+i-l2, r1 - 1, i + 1, r2,post, in, root->right); //边界条件
        
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        if(postorder.size()==0 && inorder.size()==0)
            return nullptr;
        TreeNode* root;
        Build(0,postorder.size()-1, 0, inorder.size()-1, postorder, inorder, root);
        return root;
    }
};

 

Construct Binary Tree from Inorder and Postorder Traversal