199. Binary Tree Right Side View
class Solution { public List<Integer> rightSideView(TreeNode root) { List<Integer> res=new ArrayList<Integer>(); rightView(root, res, 0); return res; } private void rightView(TreeNode node, List<Integer> res, int depth){ if(node==null) return; if(depth==res.size()) res.add(node.val); rightView(node.right, res, depth+1); rightView(node.left, res, depth+1); } }
class Solution { public List<Integer> rightSideView(TreeNode root) { List<Integer> res=new ArrayList<Integer>(); if(root==null) return res; Queue<TreeNode> que=new LinkedList<TreeNode>(); que.add(root); que.add(null); boolean right=true; while(!que.isEmpty()) { TreeNode node=que.poll(); if(node==null) { right=true; if(!que.isEmpty()) que.add(node); } else { if(right==true) { res.add(node.val); right=false; } if(node.right!=null)que.add(node.right); if(node.left!=null)que.add(node.left); } } return res; } }