重建二叉树

in 知识共享 with 0 comment

题目来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/zhong-jian-er-cha-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。

假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

示例 1:
tree.jpg

Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]

示例 2:

Input: preorder = [-1], inorder = [-1]
Output: [-1]

限制:

0 <= 节点个数 <= 5000

本人提交代码:

/**
 * 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:
    std::map<int, int> m_hashMap;
public:
    TreeNode* buildTree( const vector<int>& pre, const vector<int>& vin, int preLeft, int preRight, int inLeft, int inRight )
    {
        if ( preLeft > preRight )
            return NULL;
        
        int rootVal = pre[preLeft];
        int rootIndex = m_hashMap[rootVal];
        TreeNode* root = new TreeNode( rootVal );
        int sizeOfLeftTree = rootIndex - inLeft;
        root->left = buildTree( pre, vin, preLeft + 1, preLeft + sizeOfLeftTree, inLeft, rootIndex - 1 );
        root->right = buildTree( pre, vin, preLeft + sizeOfLeftTree + 1, preRight, rootIndex + 1, inRight );
        return root;
    }

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int size = preorder.size();
        if ( size == 0 || inorder.size() == 0 || inorder.size() != size )
            return NULL;
        
        // for root index quick access
        for ( int i = 0; i < size; i++ )
        {
            m_hashMap[inorder[i]] = i;
        }
        
        return buildTree( preorder, inorder, 0, size - 1, 0, size - 1 );
    }
};
Responses