Answered step by step
Verified Expert Solution
Link Copied!

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 8 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[[1],[1,],[2,],[1,],[5,],[11,1],[36,6],[1,],[4,]]
Top View : 1256
Complete the function topView and print the resulting values on a single line separated by space.
Input Format
You are given a function,
void topView(node * root){
}
Constraints
1 Nodes in the tree 500
Output Format
Print the values on a single line separated by space.
Sample Input
\table[[1],[1,],[2,],[1,],[5,],[11,1],[36,6],[1,],[4,]]
Sample Output
1256
Explanation
\table[[1],[1,],[2,],[1,],[5,],[11,1],[36,6],[1,],[4,]]
From the top, only nodes 1,2,5,6 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;
Node(int data){
this.data = data;
left = null;
right = null;
}
}
class Solution {
/*
class Node
int data;
Node left;
Node right;
*/
public static void topView(Node root){
}
public static Node insert(Node root, int data){
if(root == null){
return new Node(data);
} else {
Node cur;
if(data = root.data){
cur = insert(root.left, data);
root.left = cur;
} else {
cur = insert(root.right, data);
root.right = cur;
}
return root;
}
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
Node root = null;
while(t-->0){
int data = scan.nextInt();
root = insert(root, data);
}
scan.close();
topView(root);
}
}
image text in transcribed

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

Students also viewed these Databases questions