1
+
2
+
3
+ type NodeBox < T > = Option < Box < Node < T > > > ;
4
+
5
+ #[ derive( Debug ) ]
6
+ struct Node < T > {
7
+ payload : T ,
8
+ left : NodeBox < T > ,
9
+ right : NodeBox < T >
10
+ }
11
+
12
+ impl < T : PartialOrd + std:: fmt:: Display > Node < T > {
13
+ fn new ( s : T ) -> Node < T > {
14
+ Node { payload : s, left : None , right : None }
15
+ }
16
+
17
+ fn boxer ( node : Node < T > ) -> NodeBox < T > {
18
+ Some ( Box :: new ( node) )
19
+ }
20
+ fn set_left ( & mut self , node : Node < T > ) {
21
+ self . left = Self :: boxer ( node) ;
22
+ }
23
+ fn set_right ( & mut self , node : Node < T > ) {
24
+ self . right = Self :: boxer ( node) ;
25
+ }
26
+
27
+ fn insert ( & mut self , data : T ) {
28
+ if data < self . payload {
29
+ match self . left {
30
+ Some ( ref mut n) => n. insert ( data) ,
31
+ None => self . set_left ( Self :: new ( data) )
32
+ }
33
+ } else {
34
+ match self . right {
35
+ Some ( ref mut n) => n. insert ( data) ,
36
+ None => self . set_right ( Self :: new ( data) )
37
+ }
38
+ }
39
+ }
40
+
41
+ fn visit ( & self ) {
42
+ if let Some ( ref left) = self . left {
43
+ left. visit ( ) ;
44
+ }
45
+ println ! ( "'{}'" , self . payload) ;
46
+ if let Some ( ref right) = self . right {
47
+ right. visit ( ) ;
48
+ }
49
+ }
50
+ }
51
+
52
+ fn main ( ) {
53
+ let mut root = Node :: new ( "root" ) ;
54
+ root. insert ( "one" ) ;
55
+ root. insert ( "two" ) ;
56
+ root. insert ( "second" ) ;
57
+ println ! ( "arr {:#?}" , root) ;
58
+ root. visit ( ) ;
59
+ }
0 commit comments