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.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---
给出二叉树,让输出最右边能看到的元素
思路:
BFS输出每层最右边的元素
//1ms
public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
List<TreeNode> current = new ArrayList<>();
current.add(root);
while (!current.isEmpty()) {
int n = current.size();
for (int i = 0; i < n; i++) {
TreeNode node = current.remove(0);
if (i == n - 1) {
result.add(node.val);
}
if (node.left != null ) {
current.add(node.left);
}
if (node.right != null) {
current.add(node.right);
}
}
}
return result;
}