输入一棵二叉树前序遍历和中序遍历的结果,请重建该二叉树。
/** * 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: unordered_map<int, int> hash; TreeNode* build (vector<int>& pre, vector<int>& in, int pl, int pr, int il, int ir) { if (pl > pr) return NULL; auto root = new TreeNode(pre[pl]); int k = hash[root->val]; if (il < k) root->left = build (pre, in, pl + 1, k - il + pl, il, k - 1); if (k < ir) root->right = build (pre, in, k - il + pl + 1, pr, k + 1, ir); return root; } TreeNode* buildTree(vector<int>& pre, vector<int>& in) { for (int i = 0; i < in.size(); i++) { hash[in[i]] = i; } auto root = build (pre, in, 0, pre.size() - 1, 0, in.size() - 1); return root; } };
标签:pre,TreeNode,int,二叉树,il,root,pl,重建 From: https://www.cnblogs.com/leetothemoon/p/16971790.html