Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 30e433d

Browse files
committed
Completed BFS (Level Order Traversal)
1 parent 7384a22 commit 30e433d

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed

‎src/trees/BTreeLevelOrderTraversal.java‎

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
import java.util.ArrayDeque;
44
import java.util.Queue;
55

6-
import trees.InorderTraversal.Node;
7-
86
public class BTreeLevelOrderTraversal {
97

108
static class Node{
@@ -32,6 +30,8 @@ public static void main(String[] args) {
3230
tree.root.left.left = new Node(25);
3331
tree.root.left.right = new Node(75);
3432
tree.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

3636
level_traverse(tree.root);
3737

@@ -40,15 +40,34 @@ public static void main(String[] args) {
4040
private static void level_traverse(Node root2) {
4141

4242
if (root2==null) System.out.println("Tree is empty");
43+
4344
Queue<Node> curr = new ArrayDeque<>();
45+
Node null_node = new Node(0);
46+
47+
curr.add(root2);
48+
curr.add(null_node);
4449

4550
while(!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
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /