1
+ public class TreeNode
2
+ {
3
+ public int val ;
4
+ public TreeNode left ;
5
+ public TreeNode right ;
6
+ public TreeNode ( int val = 0 , TreeNode left = null , TreeNode right = null )
7
+ {
8
+ this . val = val ;
9
+ this . left = left ;
10
+ this . right = right ;
11
+ }
12
+ }
13
+
14
+ public class Solution
15
+ {
16
+ public TreeNode ConstructFromPrePost ( int [ ] preorder , int [ ] postorder )
17
+ {
18
+ Dictionary < int , int > postToIndex = new Dictionary < int , int > ( ) ;
19
+
20
+ for ( int i = 0 ; i < postorder . Length ; ++ i )
21
+ postToIndex [ postorder [ i ] ] = i ;
22
+
23
+ return Build ( preorder , 0 , preorder . Length - 1 , postorder , 0 , postorder . Length - 1 , postToIndex ) ;
24
+ }
25
+
26
+ private TreeNode Build ( int [ ] pre , int preStart , int preEnd , int [ ] post , int postStart ,
27
+ int postEnd , Dictionary < int , int > postToIndex )
28
+ {
29
+ if ( preStart > preEnd )
30
+ return null ;
31
+ if ( preStart == preEnd )
32
+ return new TreeNode ( pre [ preStart ] ) ;
33
+
34
+ int rootVal = pre [ preStart ] ;
35
+ int leftRootVal = pre [ preStart + 1 ] ;
36
+ int leftRootPostIndex = postToIndex [ leftRootVal ] ;
37
+ int leftSize = leftRootPostIndex - postStart + 1 ;
38
+
39
+ TreeNode root = new TreeNode ( rootVal ) ;
40
+ root . left = Build ( pre , preStart + 1 , preStart + leftSize , post , postStart , leftRootPostIndex ,
41
+ postToIndex ) ;
42
+ root . right = Build ( pre , preStart + leftSize + 1 , preEnd , post , leftRootPostIndex + 1 ,
43
+ postEnd - 1 , postToIndex ) ;
44
+ return root ;
45
+ }
46
+ }
0 commit comments