Skip to content

Instantly share code, notes, and snippets.

@wohhie
Last active July 11, 2021 14:36
Show Gist options
  • Select an option

  • Save wohhie/e44b5c643b68bc7d251bc074f02adc7d to your computer and use it in GitHub Desktop.

Select an option

Save wohhie/e44b5c643b68bc7d251bc074f02adc7d to your computer and use it in GitHub Desktop.
private void levelOrder(Node node){
// 1. print the root data
// 2. insert root address in queue
// 3. while queue is not empty
// a. get the address of the queue
// check left child has data
// i. print the left child data
// j. insert data of left child
// else check right child has data
// i. print the right child data
// j. insert data of the right child
// timecomplexity = o(n)
// spacecomplexity = o(n)
Queue<Node> queue = new LinkedList<>();
System.out.print(node.data + " ");
queue.add(node);
while (!queue.isEmpty()){
node = queue.remove();
if (node.left != null){
System.out.print(node.left.data + " ");
queue.add(node.left);
}
if(node.right != null){
System.out.print(node.right.data + " ");
queue.add(node.right);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment