LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal

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

Note:
You may assume that duplicates do not exist in the tree.

For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7


和105一样,稍微改一下就好了、
class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        
        vector<int> leftpost;
        vector<int> leftino;
        vector<int> rightpost;
        vector<int> rightino;
        
        if(postorder.empty()||inorder.empty())
            return NULL;
        int root = postorder[postorder.size()-1]; int left=0;int right=0;int tag=0;
        for(int i=0;i<inorder.size();i++)
        {
            if(inorder[i]==root)
            {
                tag=1;
            }
            else if(tag==0)
            {left++;leftino.push_back(inorder[i]);}
            else
            {right++;rightino.push_back(inorder[i]);}
        }
        for(int i=0;i<left;i++)
        {
            leftpost.push_back(postorder[i]);
        }
        for(int i=left;i<postorder.size()-1;i++)
        {
            rightpost.push_back(postorder[i]);
        }
        
        TreeNode* tree = new TreeNode(root);
       
        tree->left = buildTree(leftino,leftpost);
        tree->right = buildTree(rightino,rightpost);
        
        return tree;
        
        
    }
};

猜你喜欢

转载自www.cnblogs.com/dacc123/p/9218959.html