|
| 1 | +/* |
| 2 | + * @lc app=leetcode id=105 lang=cpp |
| 3 | + * |
| 4 | + * [105] Construct Binary Tree from Preorder and Inorder Traversal |
| 5 | + */ |
| 6 | + |
| 7 | +// @lc code=start |
| 8 | +/** |
| 9 | + * Definition for a binary tree node. |
| 10 | + * struct TreeNode { |
| 11 | + * int val; |
| 12 | + * TreeNode *left; |
| 13 | + * TreeNode *right; |
| 14 | + * TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 15 | + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 16 | + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 17 | + * }; |
| 18 | + */ |
| 19 | +class Solution { |
| 20 | + unordered_map<int, int> valToIndex; |
| 21 | +public: |
| 22 | + TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { |
| 23 | + for (int i = 0; i < inorder.size(); i++) { |
| 24 | + valToIndex[inorder[i]] = i; |
| 25 | + } |
| 26 | + return build(preorder, 0, preorder.size() - 1, |
| 27 | + inorder, 0, inorder.size() - 1); |
| 28 | + } |
| 29 | + |
| 30 | + TreeNode* build(vector<int>& preorder, int preStart, int preEnd, |
| 31 | + vector<int>& inorder, int inStart, int inEnd) { |
| 32 | + if (preStart > preEnd) { |
| 33 | + return nullptr; |
| 34 | + } |
| 35 | + |
| 36 | + // root 节点对应的值就是前序遍历数组的第一个元素 |
| 37 | + int rootVal = preorder[preStart]; |
| 38 | + // rootVal 在中序遍历数组中的索引 |
| 39 | + int index = valToIndex[rootVal]; |
| 40 | + |
| 41 | + int leftSize = index - inStart; |
| 42 | + |
| 43 | + // 先构造出当前根节点 |
| 44 | + TreeNode* root = new TreeNode(rootVal); |
| 45 | + // 递归构造左右子树 |
| 46 | + root->left = build(preorder, preStart + 1, preStart + leftSize, |
| 47 | + inorder, inStart, index - 1); |
| 48 | + |
| 49 | + root->right = build(preorder, preStart + leftSize + 1, preEnd, |
| 50 | + inorder, index + 1, inEnd); |
| 51 | + return root; |
| 52 | + } |
| 53 | +}; |
| 54 | +// @lc code=end |
| 55 | + |
0 commit comments