Total Accepted: 34521
Total Submissions: 104860
Difficulty: Medium
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]
.
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Show Similar Problems
Have you met this question in a real interview?
Yes
No
求一棵二叉树的右视图。用BFS的方式遍历二叉树,取每层的最后一个节点。
我的AC代码
public class BinaryTreeRightSideView {
public static void main(String[] args) {
TreeNode n1 = new TreeNode(2);
TreeNode n2 = new TreeNode(1);
n1.left = n2;
System.out.println(rightSideView(n1));
}
public static List<Integer> rightSideView(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if(root == null) return list;
Queue<TreeNode> queue = new ArrayDeque<TreeNode>();
queue.add(root);
queue.add(new TreeNode(Integer.MIN_VALUE));
if(root.left != null) queue.add(root.left);
if(root.right != null) queue.add(root.right);
TreeNode pre = queue.poll();
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
if(cur.val == Integer.MIN_VALUE) {
list.add(pre.val);
if(!queue.isEmpty()) queue.add(new TreeNode(Integer.MIN_VALUE));
} else {
if(cur.left != null) queue.add(cur.left);
if(cur.right != null) queue.add(cur.right);
pre = cur;
}
}
return list;
}
}