1
+ namespace BenchmarkGameBTrees
2
+ {
3
+ /*
4
+ The Computer Language Benchmarks Game
5
+ https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
6
+
7
+ contributed by Marek Safar
8
+ optimized by kasthack
9
+ *reset*
10
+ */
11
+ using System ;
12
+ using System . Threading ;
13
+ using System . Threading . Tasks ;
14
+
15
+ class BinaryTrees
16
+ {
17
+ const int minDepth = 4 ;
18
+ public static void Main ( String [ ] args )
19
+ {
20
+ int n = 0 ;
21
+ if ( args . Length > 0 ) n = Int32 . Parse ( args [ 0 ] ) ;
22
+ int maxDepth = Math . Max ( minDepth + 2 , n ) ;
23
+ int stretchDepth = maxDepth + 1 ;
24
+ int check = ( TreeNode . bottomUpTree ( stretchDepth ) ) . itemCheck ( ) ;
25
+ Console . WriteLine ( "stretch tree of depth {0}\t check: {1}" , stretchDepth , check ) ;
26
+ TreeNode longLivedTree = TreeNode . bottomUpTree ( maxDepth ) ;
27
+ for ( int depth = minDepth ; depth <= maxDepth ; depth += 2 )
28
+ {
29
+ int iterations = 1 << ( maxDepth - depth + minDepth ) ;
30
+ check = 0 ;
31
+
32
+ Parallel . For ( 1 , iterations + 1 ,
33
+ ( ) => 0 ,
34
+ ( i , loop , localCheck ) =>
35
+ {
36
+ return localCheck +
37
+ ( TreeNode . bottomUpTree ( depth ) ) . itemCheck ( ) ;
38
+ } ,
39
+ localCheck => Interlocked . Add ( ref check , localCheck )
40
+ ) ;
41
+
42
+ Console . WriteLine ( "{0}\t trees of depth {1}\t check: {2}" ,
43
+ iterations , depth , check ) ;
44
+ }
45
+ Console . WriteLine ( "long lived tree of depth {0}\t check: {1}" ,
46
+ maxDepth , longLivedTree . itemCheck ( ) ) ;
47
+ }
48
+
49
+ class TreeNode
50
+ {
51
+ private TreeNode left , right ;
52
+
53
+ internal static TreeNode bottomUpTree ( int depth )
54
+ {
55
+ TreeNode t ;
56
+ ChildTreeNodes ( out t , depth ) ;
57
+ return t ;
58
+ }
59
+ static void ChildTreeNodes ( out TreeNode node , int depth )
60
+ {
61
+ node = new TreeNode ( ) ;
62
+ if ( depth > 0 )
63
+ {
64
+ ChildTreeNodes ( out node . left , depth - 1 ) ;
65
+ ChildTreeNodes ( out node . right , depth - 1 ) ;
66
+ }
67
+ }
68
+ internal int itemCheck ( )
69
+ {
70
+ if ( right == null ) return 1 ;
71
+ else return 1 + left . itemCheck ( ) + right . itemCheck ( ) ;
72
+ }
73
+ }
74
+ }
75
+ }
0 commit comments