Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Financial management theory and practice

Authors: Eugene F. Brigham and Michael C. Ehrhardt

12th Edition

978-0030243998, 30243998, 324422695, 978-0324422696

Students also viewed these Programming questions