Binary Tree and BST Questions
Binary Tree and BST Questions
class Pair
{
Node node;
Integer height;
Pair(Node node,Integer height)
{
this.node=node;
this.height=height;
}
}
class Solution
{
class Pair
{
Node node;
Integer height;
Pair(Node node,Integer height)
{
this.node=node;
this.height=height;
}
}
class Solution
{
//Function to return a list containing the bottom view of the given tree.
public ArrayList <Integer> bottomView(Node root)
{
ArrayList<Integer>a1=new ArrayList<>();
TreeMap<Integer,Node>treeMap=new TreeMap<>();
if(root==null)
return a1;
Queue<Pair>q1=new LinkedList<>();
q1.add(new Pair(root,0));
treeMap.put(0,root);
while(q1.isEmpty()==false)
{
Pair top=q1.poll();
Node n1=top.node;
int h1=top.height;
if(n1.left!=null)
{
if(treeMap.containsKey(h1-1)==false || treeMap.containsKey(h1-
1)==true)
{
treeMap.put(h1-1,n1.left);
}
q1.add(new Pair(n1.left,h1-1));
}
if(n1.right!=null)
{
if(treeMap.containsKey(h1+1)==false ||
treeMap.containsKey(h1+1)==true)
{
treeMap.put(h1+1,n1.right);
}
q1.add(new Pair(n1.right,h1+1));
}
}
for(Node temp:treeMap.values())
{
a1.add(temp.data);
}
return a1;
}
}