leetcode 从前序与中序遍历序列构造二叉树

leetcode 从前序与中序遍历序列构造二叉树_第1张图片

 

/**
 * 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 {
private:
    unordered_map<int,int>IndexMappIndex;
public:
    TreeNode* buildTree1(vector<int>& preorder,int preleft,int preright,int inleft,int inright)
    {
        if(preleft>preright || inleft>inright )return NULL;
        TreeNode *root=new TreeNode(preorder[preleft]);
        int pIndex=IndexMappIndex[preorder[preleft]];
        root->left=buildTree1(preorder,preleft+1,pIndex-inleft+preleft,inleft,pIndex-1);
        root->right=buildTree1(preorder,pIndex-inleft+preleft+1,preright,pIndex+1,inright);
        return root;
    }

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        if(preorder.size()!=inorder.size() || preorder.size()<1 || inorder.size()<1)
        {
            return NULL;
        }
        
        for(int i=0;i)
        {
            IndexMappIndex[inorder[i]]=i;
        }
        return buildTree1(preorder,0,preorder.size()-1,0,inorder.size()-1);
    }

};

 

你可能感兴趣的:(leetcode 从前序与中序遍历序列构造二叉树)