Question: Derive a O ( n ) method valuesInLevelOrder() that returns a list of the nodes of a binary tree in level-order. That is, the method

Derive a O(n) method valuesInLevelOrder() that returns a list of the nodes of a binary tree in level-order. That is, the method should return the root, then the nodes at depth 1, followed by the nodes at depth 2, and so on. Your algorithm should begin by putting the tree root on an initially empty queue. Then dequeue a node, add it to the output, and enqueue its left and right children (if they exist). Repeat until the queue is empty.

Node.java

import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue;

public class Node { E data; Node leftChild; Node rightChild;

public Node() {

}

public Node(E data) { this.data = data; }

public Node(Node left, Node right) { this.leftChild = left; this.rightChild = right; }

public Node(E data, Node left, Node right) { this.data = data; this.leftChild = left; this.rightChild = right; }

public static List valuesInLevelOrder(Node root) { List result = new ArrayList<>(); if (root == null) { return result; Queue> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { Node current = queue.poll(); result.add(current.data); if (current.leftChild != null) { queue.add(current.leftChild); if (current.rightChild != null) { queue.add(current.rightChild); } return result;

}

public static void main(String [] args) {

} }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!