Binary Tree Right Side View (M)
题目
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 <---
题意
站在一个二叉树的右边向左看,求从上到下能看到的所有元素。
思路
相当于取每一行的最右元素,层序遍历即可。
代码实现
Java
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> ans = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
if (root != null) {
q.offer(root);
}
while (!q.isEmpty()) {
int size = q.size();
TreeNode cur = null;
while (size > 0) {
cur = q.poll();
if (cur.left != null) q.offer(cur.left);
if (cur.right != null) q.offer(cur.right);
size--;
}
ans.add(cur.val);
}
return ans;
}
}