Created
July 5, 2016 00:24
-
-
Save meghakrishnamurthy/a06f74eb2254425ce4a0169bb5b50563 to your computer and use it in GitHub Desktop.
BFS or Level order traversal of binary tree - implementation in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package megha.codingproblem.trees; | |
import java.util.LinkedList; | |
import java.util.Queue; | |
/** | |
* Class to perform a level order traversal or BFS on a binary tree | |
* Time complexity - O(n) | |
* Space complexity - Average of O(1) and worst case of O(n) | |
* @author megha krishnamurthy | |
* | |
*/ | |
public class LevelOrderTraversal { | |
public void levelOrderTraversal(Node root) { | |
if(root == null) { | |
return; | |
} | |
Queue<Node> nodeQueue = new LinkedList<Node>(); | |
nodeQueue.add(root); | |
while(!nodeQueue.isEmpty()) { | |
Node currentNode = nodeQueue.remove(); | |
System.out.print(currentNode.data + " "); | |
if(currentNode.left != null) { | |
nodeQueue.add(currentNode.left); | |
} | |
if(currentNode.right != null) { | |
nodeQueue.add(currentNode.right); | |
} | |
} | |
} | |
public static void main(String args[]) { | |
Node root = new Node(10); | |
root.left = new Node(6); | |
root.right = new Node(21); | |
root.left.left = new Node(1); | |
root.left.right = new Node(8); | |
root.right.left = new Node(13); | |
root.right.right = new Node(25); | |
root.right.left.left = new Node (12); | |
root.right.left.right = new Node(18); | |
LevelOrderTraversal levelTraversal = new LevelOrderTraversal(); | |
levelTraversal.levelOrderTraversal(root); | |
} | |
} | |
private class Node { | |
int data; | |
Node left; | |
Node right; | |
private Node(int value) { | |
data = value; | |
left = right = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment