Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
1 <--- / 2 3 <--- 5 4 <---
You should return [1, 3, 4]
.
/** * 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) { //层序遍历,每次获取每一层最后的节点,并将其保存在结果 LinkedList<TreeNode> queue=new LinkedList<TreeNode>(); List<Integer> res=new ArrayList<Integer>(); if(root==null) return res; queue.add(root); while(!queue.isEmpty()){ int count=queue.size(); res.add(queue.get(count-1).val); for(int i=0;i<count;i++){ TreeNode temp=queue.remove(); if(temp.left!=null) queue.add(temp.left); if(temp.right!=null) queue.add(temp.right); } } return res; } }