1. 程式人生 > >106 Construct Binary Tree from Inorder and Postorder Traversal 從中序與後序遍歷序列構造二叉樹

106 Construct Binary Tree from Inorder and Postorder Traversal 從中序與後序遍歷序列構造二叉樹

etc emp gpo 構造 inorder lee UC from ons

給定一棵樹的中序遍歷與後序遍歷,依據此構造二叉樹。
註意:
你可以假設樹中沒有重復的元素。
例如,給出
中序遍歷 = [9,3,15,20,7]
後序遍歷 = [9,15,7,20,3]
返回如下的二叉樹:
3
/ \
9 20
/ \
15 7
詳見:https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/

/**
 * 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) {
        int is=inorder.size();
        if(is==0||inorder.empty())
        {
            return nullptr;
        }
        int val=postorder[is-1];
        TreeNode* root=new TreeNode(val);
        vector<int> in_left,in_right,post_left,post_right;
        int p=0;
        for(;p<is;++p)
        {
            if(inorder[p]==val)
            {
                break;
            }
        }
        for(int i=0;i<is;++i)
        {
            if(i<p)
            {
                in_left.push_back(inorder[i]);
                post_left.push_back(postorder[i]);
            }
            else if(i>p)
            {
                in_right.push_back(inorder[i]);
                post_right.push_back(postorder[i-1]);
            }
        }
        root->left=buildTree(in_left,post_left);
        root->right=buildTree(in_right,post_right);
        return root;
    }
};

106 Construct Binary Tree from Inorder and Postorder Traversal 從中序與後序遍歷序列構造二叉樹