## [Leetcode]105. Construct Binary Tree from Preorder and Inorder Traversal (C++)

### 题目描述

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

### Note

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

### 解题思路

• inorder：根节点 —-> 左子树 —-> 右子树，所以给定一个二叉树的 inorder 顺序遍历结果，可以知道第一个节点是根节点
• preorder：左子树 —-> 根节点 —-> 右子树，所以给定一个二叉树的 preorder 顺序便利结果，假如可以知道根节点的位置，那么根节点左侧节点全为左子树，根节点右侧节点全为右子树

``````/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode() : val(0), left(nullptr), right(nullptr) {}
*     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
*     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
#include <unordered_map>
#include <vector>

class Solution {
public:
TreeNode* buildTree(std::vector<int>& preorder, std::vector<int>& inorder) {
std::unordered_map<int, int> inorder_map;
for (size_t i = 0; i < inorder.size(); ++i) {
inorder_map[inorder[i]] = i;
}
return buildTree(preorder, inorder, 0, preorder.size() - 1, 0,
inorder.size() - 1, inorder_map);
}

private:
TreeNode* buildTree(const std::vector<int>& preorder,
const std::vector<int>& inorder, int preorder_begin,
int preorder_end, int inorder_begin, int inorder_end,
std::unordered_map<int, int>& inorder_map) {
if (preorder_end < preorder_begin || inorder_end < inorder_begin)
return nullptr;
TreeNode* root = new TreeNode(preorder[preorder_begin]);
int root_idx = inorder_map[root->val];
int left_len = root_idx - inorder_begin;
int right_len = inorder_end - root_idx;
root->left = buildTree(preorder, inorder, preorder_begin + 1,
preorder_begin + left_len, inorder_begin,
root_idx - 1, inorder_map);
root->right =
buildTree(preorder, inorder, preorder_begin + left_len + 1,
preorder_end, root_idx + 1, inorder_end, inorder_map);

return root;
}
};
``````
• 时间复杂度: O(n)
• 空间复杂度: O(n)

Built with Hugo
Theme Stack designed by Jimmy