6 Rebuild the binary tree

Enter the results of preorder traversal and inorder traversal of a binary tree, and reconstruct the binary tree. It is assumed that the results of the input preorder traversal and inorder traversal do not contain duplicate numbers. For example, input the preorder traversal sequence {1,2,4,7,3,5,6,8} and the inorder traversal sequence {4,7,2,1,5,3,8,6}, then rebuild the binary tree and return.

The first value of the pre-order traversal is the value of the root node. Use this value to divide the in-order traversal result into two parts. The left part is the in-order traversal result of the left subtree of the tree, and the right part is the in-order traversal of the right subtree of the tree. the result of.

 

 

 

 

C++:

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 private:
12     unordered_map<int,int> inOrderIndex ;//中序遍历每个值对应的索引
13 public:
14     TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) {
15         for(int i = 0 ; i < in.size() ; i++){
16             inOrderIndex[in[i]] = i ; 
17         }
18         return reConstructBinaryTree(pre,0,pre.size()-1,in,0,in.size()-1) ;
19     }
20     
21     TreeNode* reConstructBinaryTree(vector<int> pre ,intpreL , int preR ,
 22                                      vector< int > in , int inL , int inR ){
 23          TreeNode* root = new TreeNode(pre[preL]) ; // The first value of the preorder traversal is the value of the root node 
24          if (preL == preR)
 25              return root ;
 26          if (preL > preR || inL > inR)
 27              return NULL ;
 28          int index = inOrderIndex[pre[preL]] ; // The position of the root node in the in-order traversal 
29          int leftLen = index - inL ;//左子树的大小
30         root->left = reConstructBinaryTree(pre,preL+1,preL+leftLen,in,inL,inL+leftLen-1) ;
31         root->right = reConstructBinaryTree(pre,preL+leftLen+1,preR,in,inL+leftLen+1,inR) ;
32         return root ;
33     }
34 };

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324696298&siteId=291194637