File tree Expand file tree Collapse file tree 1 file changed +25
-6
lines changed
Expand file tree Collapse file tree 1 file changed +25
-6
lines changed Original file line number Diff line number Diff line change 33import java .util .ArrayDeque ;
44import java .util .Queue ;
55
6- import trees .InorderTraversal .Node ;
7-
86public class BTreeLevelOrderTraversal {
97
108static class Node {
@@ -32,6 +30,8 @@ public static void main(String[] args) {
3230tree .root .left .left = new Node (25 );
3331tree .root .left .right = new Node (75 );
3432tree .root .right .right = new Node (350 );
33+ tree .root .right .right .right = new Node (380 );
34+ tree .root .right .right .left = new Node (320 );
3535
3636level_traverse (tree .root );
3737
@@ -40,15 +40,34 @@ public static void main(String[] args) {
4040private static void level_traverse (Node root2 ) {
4141
4242if (root2 ==null ) System .out .println ("Tree is empty" );
43+
4344Queue <Node > curr = new ArrayDeque <>();
45+ Node null_node = new Node (0 );
46+
47+ curr .add (root2 );
48+ curr .add (null_node );
4449
4550while (!curr .isEmpty ()){
46- curr .add (root2 );
51+
52+ if (curr .peek ().left !=null ){
53+ curr .add (curr .peek ().left );
54+ }
55+
56+ if (!(curr .peek ().right ==null )){
57+ curr .add (curr .peek ().right );
58+ }
59+
60+ System .out .print (curr .poll ().data +"," );
61+
62+ if (curr .peek ()==null_node ){
63+ System .out .println ("" );
64+ curr .poll ();
65+ if (!curr .isEmpty ()){
66+ curr .add (null_node );
67+ }
68+ }
4769
4870}
49-
50-
51-
5271}
5372
5473}
You can’t perform that action at this time.
0 commit comments