Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save codetalks-new/d1f5ecdea5d3656ce14e to your computer and use it in GitHub Desktop.
Save codetalks-new/d1f5ecdea5d3656ce14e to your computer and use it in GitHub Desktop.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> arr = new ArrayList<Integer>();
if(root == null){
return arr;
}
List<TreeNode> oneLevel = new ArrayList<TreeNode>();
List<TreeNode> nextLevel = new ArrayList<TreeNode>();
oneLevel.add(root);
arr.add(root.val);
while(!oneLevel.isEmpty()){
TreeNode current = oneLevel.remove(0) ;
if(current.left != null){
nextLevel.add(current.left);
}
if(current.right != null){
nextLevel.add(current.right);
}
if(oneLevel.isEmpty()){
if(!nextLevel.isEmpty()){
TreeNode last = nextLevel.get(nextLevel.size() - 1);
arr.add(last.val);
oneLevel = nextLevel;
nextLevel = new ArrayList<TreeNode>();
}
}
}
return arr;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment