Top View of Binary Tree
Explanation:
Maintain a set so that we will get to know if this is the first tree node coming with distance x and print it.
Code:
class treevertical
{
TreeNode node;
public int hd;
treevertical(TreeNode t,int hd)
{
node=t;
this.hd=hd;
}
}
class Hackerranksolutionc
{
public void printTopView(TreeNode root)
{
if(root==null)
return;
Set<Integer> s=new HashSet<Integer>();
Deque<treevertical> m=new ArrayDeque<treevertical>();
m.add(new treevertical(root,0));
while(!m.isEmpty())
{
treevertical t= m.removeFirst() ;
TreeNode Node=t.node;
int lvl=t.hd;
if(!s.contains(lvl))
{System.out.print(Node.key+" ");
s.add(lvl);
}
if(Node.left!=null)
m.add(new treevertical(Node.left,t.hd-1));
if(Node.right!=null)
m.add(new treevertical(Node.right,t.hd+1));
}
}
}
Approach 2: Using Less Space and Time
void topView(Node root) {
if(root==null)
return;
Deque<Node> m=new ArrayDeque<Node>();
Node left=root.left;
while(left!=null)
{
m.addFirst(left);
left=left.left;
}
m.add(root);
Node right=root.right;
while(right!=null)
{
m.add(right);
right=right.right;
}
while(!m.isEmpty())
{
System.out.print(m.poll().data+" ");
}
}
Maintain a set so that we will get to know if this is the first tree node coming with distance x and print it.
Code:
class treevertical
{
TreeNode node;
public int hd;
treevertical(TreeNode t,int hd)
{
node=t;
this.hd=hd;
}
}
class Hackerranksolutionc
{
public void printTopView(TreeNode root)
{
if(root==null)
return;
Set<Integer> s=new HashSet<Integer>();
Deque<treevertical> m=new ArrayDeque<treevertical>();
m.add(new treevertical(root,0));
while(!m.isEmpty())
{
treevertical t= m.removeFirst() ;
TreeNode Node=t.node;
int lvl=t.hd;
if(!s.contains(lvl))
{System.out.print(Node.key+" ");
s.add(lvl);
}
if(Node.left!=null)
m.add(new treevertical(Node.left,t.hd-1));
if(Node.right!=null)
m.add(new treevertical(Node.right,t.hd+1));
}
}
}
Approach 2: Using Less Space and Time
void topView(Node root) {
if(root==null)
return;
Deque<Node> m=new ArrayDeque<Node>();
Node left=root.left;
while(left!=null)
{
m.addFirst(left);
left=left.left;
}
m.add(root);
Node right=root.right;
while(right!=null)
{
m.add(right);
right=right.right;
}
while(!m.isEmpty())
{
System.out.print(m.poll().data+" ");
}
}
0 Comments:
Post a Comment