File tree 2 files changed +75
-0
lines changed
2 files changed +75
-0
lines changed Original file line number Diff line number Diff line change
1
+ using System ;
2
+ using System . Collections . Generic ;
3
+ using System . Linq ;
4
+ using System . Text ;
5
+
6
+ namespace Tree . TreeLib
7
+ {
8
+ public class LevelTraversalTree
9
+ {
10
+ public IList < IList < int > > LevelOrder ( TreeNode root )
11
+ {
12
+ if ( root == null )
13
+ return new List < IList < int > > ( ) ;
14
+ IList < IList < int > > rtn = new List < IList < int > > { new List < int > { root . val } } ;
15
+ var tmp = getNextLevel ( new List < TreeNode > { root } ) ;
16
+ if ( tmp != null && tmp . Count > 0 )
17
+ {
18
+ foreach ( var item in tmp )
19
+ rtn . Add ( item ) ;
20
+ }
21
+ return rtn ;
22
+ }
23
+ private IList < IList < int > > getNextLevel ( IList < TreeNode > curLevel )
24
+ {
25
+ if ( curLevel == null || curLevel . Count == 0 )
26
+ return null ;
27
+ IList < IList < int > > rtn = new List < IList < int > > ( ) ;
28
+ List < TreeNode > nextn = new List < TreeNode > ( ) ;
29
+ foreach ( var item in curLevel )
30
+ {
31
+ if ( item . left != null )
32
+ nextn . Add ( item . left ) ;
33
+ if ( item . right != null )
34
+ nextn . Add ( item . right ) ;
35
+ }
36
+ if ( nextn . Count == 0 )
37
+ return null ;
38
+ rtn . Add ( nextn . Select ( r => r . val ) . ToList ( ) ) ;
39
+ var children = getNextLevel ( nextn ) ;
40
+ if ( children != null && children . Count > 0 )
41
+ {
42
+ foreach ( var item in children )
43
+ rtn . Add ( item ) ;
44
+ }
45
+ return rtn ;
46
+ }
47
+ }
48
+ }
Original file line number Diff line number Diff line change
1
+ using System ;
2
+ using System . Collections . Generic ;
3
+ using System . Linq ;
4
+ using System . Text ;
5
+
6
+ namespace Tree . TreeLib
7
+ {
8
+ //二叉树的遍历,迭代版
9
+ public class TravesalUsingStack
10
+ {
11
+ public void PreOrder ( TreeNode root )
12
+ {
13
+ if ( root == null )
14
+ return ;
15
+ Stack < TreeNode > s = new Stack < TreeNode > ( ) ;
16
+ s . Push ( root ) ;
17
+ Console . WriteLine ( root . val ) ;
18
+ while ( s . Count > 0 )
19
+ {
20
+ TreeNode node = ( s . Peek as TreeNode ) . left ;
21
+
22
+
23
+ }
24
+ }
25
+
26
+ }
27
+ }
You can’t perform that action at this time.
0 commit comments