/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ classSolution { public:
unordered_map<int,int> pos;
TreeNode * build(vector<int>& preorder, vector<int>& inorder, int a, int b, int x, int y){ // 如果区间为空(若 a == b ,比如 9 == 9,此时依旧要创建 根为9 的节点) if(a > b) returnNULL;
// 先构建根节点 TreeNode * root = newTreeNode(preorder[a]); // 找到中序遍历中根节点的位置 int k = pos[root -> val]; // 递归创建左子树和右子树 root -> left = build(preorder, inorder, a + 1, k - x + a, x, k - 1); root -> right = build(preorder, inorder, b - y + k + 1, b, k + 1, y); return root; }
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder){ int len = inorder.size(); // 提前记录中序遍历每个元素的位置 for(int i = 0; i < len; i++) pos[inorder[i]] = i;
returnbuild(preorder, inorder, 0, len - 1, 0, len - 1); } };