Answered step by step
Verified Expert Solution
Question
1 Approved Answer
I need help with this Java question: Tree: Top View. We are govegiven a code to work with and please use Java 8 to answer
I need help with this Java question: Tree: Top View. We are govegiven a code to work with and please use Java to answer the question. Please make sure your code works and provide output if you can. Here is the question.
Given a pointer to the root of a binary tree, print the top view of the binary tree.
The tree as seen from the top the nodes, is called the top view of the tree.
For example :
table
Top View :
Complete the function topView and print the resulting values on a single line separated by space.
Input Format
You are given a function,
void topViewnode root
Constraints
Nodes in the tree
Output Format
Print the values on a single line separated by space.
Sample Input
table
Sample Output
Explanation
table
From the top, only nodes are visible.
Here is the code we are given to work with.
import java.util.;
import java.io;
class Node
Node left;
Node right;
int data;
Nodeint data
this.data data;
left null;
right null;
class Solution
class Node
int data;
Node left;
Node right;
public static void topViewNode root
public static Node insertNode root, int data
ifroot null
return new Nodedata;
else
Node cur;
ifdata root.data
cur insertrootleft, data;
root.left cur;
else
cur insertrootright, data;
root.right cur;
return root;
public static void mainString args
Scanner scan new ScannerSystemin;
int t scan.nextInt;
Node root null;
whilet
int data scan.nextInt;
root insertroot data;
scan.close;
topViewroot;
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started