6 重建二叉树

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

前序遍历的第一个值为根节点的值,使用这个值将中序遍历结果分成两部分,左部分为树的左子树中序遍历结果,右部分为树的右子树中序遍历的结果。

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 ,int preL , int preR ,
22                                     vector<int> in ,int inL , int inR ){
23         TreeNode* root = new TreeNode(pre[preL]) ;//前序遍历的第一个值为根节点的值
24         if (preL == preR)
25             return root ;
26         if (preL > preR || inL > inR)
27             return NULL ;
28         int index = inOrderIndex[pre[preL]] ;//根节点在中序遍历的位置
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 };

java:

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 import java.util.*;
11 public class Solution {
12     private Map<Integer,Integer> map = new HashMap<>() ;
13     
14     public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
15         for(int i = 0 ; i < pre.length ; i++){
16             map.put(in[i] , i) ;
17         }
18         return reConstructBinaryTree(pre , 0 , pre.length-1 , 0) ;
19     }
20     
21     public TreeNode reConstructBinaryTree(int [] pre,int preL , int preR , int inL) {
22         if (preL > preR)
23             return null ;
24         TreeNode root = new TreeNode(pre[preL]) ;
25         int index = map.get(root.val) ;
26         int leftLen = index - inL ;
27         root.left = reConstructBinaryTree(pre , preL+1 , preL+leftLen , inL) ;
28         root.right = reConstructBinaryTree(pre , preL+leftLen+1 , preR , inL+leftLen+1) ;
29         return root ;
30     }
31 }
原文地址:https://www.cnblogs.com/mengchunchen/p/8906917.html