Skip to content

Instantly share code, notes, and snippets.

@pramodvspk
Created March 14, 2017 22:25
Show Gist options
  • Save pramodvspk/ade337fb73d7eb3342563cd9be8777bc to your computer and use it in GitHub Desktop.
Save pramodvspk/ade337fb73d7eb3342563cd9be8777bc to your computer and use it in GitHub Desktop.
Printing right side view of a Binary Tree
public List<Integer> rightSideView(TreeNode root) {
if(root==null) return new ArrayList();
/*Initializing a ArrayList to return*/
List<Integer> returnList = new ArrayList<Integer>();
/*Initializing a Queue to hold elements*/
Queue<TreeNode> q = new LinkedList<TreeNode>();
/*Creating a dummy variable*/
TreeNode current = null;
/*Adding the root and null into the Queue*/
q.add(root);
q.add(null);
/*Looping through the queue while its size is greater than 1 [because in the end there will be a null and we might go into infinite loop]*/
while(q.size()>1){
/*Remove the element at the head*/
current = q.remove();
if(current!=null){
if(current.left!=null) q.add(current.left);
if(current.right!=null) q.add(current.right);
/*If the next element is null then this is the right most element visible so add it*/
if(q.peek()==null) returnList.add(current.val);
}else{
q.add(null);
}
}
return returnList;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment