Pre-knowledge : The traversal method is classified according to the position of the root node, pre-order traversal (left and right root), middle-order traversal (left root and right), post-order traversal (left and right root). For tree level traversal, it is the way to find BFS Traverse, add a NULL after each leaf node (as shown in the figure)
Given the pre-order and middle-order, we can determine a tree recursively by dfs. Take the example in the figure. First, the pre-order (left and right), then 3 must be the root node, so see where the 3 traversed by the middle-order is Position, because the middle order traversal is left root right, so the 9 before 3 is the left subtree, and the 15 20 7 after 3 is the right subtree
The first traversal of the right subtree is 20, then 20 is the root node of the right subtree, the 15 before 20 in the mid-order traversal is the left subtree of 20, and 7 is the right subtree of 20, and the same is the left subtree The same
In this way, dfs recursion can be realized, but the boundary problem must be considered clearly, that is, the length of the recursion interval
Code
/**
* 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> mp;
TreeNode *dfs(vector<int> preorder, vector<int> inorder,int pl,int pr,int il,int ir){
if(pl > pr)returnNULL;int k = mp[preorder[pl]];//中序遍历的根节点下标
TreeNode *root =newTreeNode(inorder[k]);
root->left =dfs(preorder, inorder, pl +1, pl +1+ k - il -1, il, il + k -1);
root->right =dfs(preorder, inorder, pl +1+ k - il -1+1, pr, k +1, ir);return root;}
TreeNode*buildTree(vector<int>& preorder, vector<int>& inorder){
int n = preorder.size();for(int i =0; i < inorder.size(); i++) mp[inorder[i]]= i;returndfs(preorder, inorder,0, n -1,0, n -1);}};