二叉树的层序遍历,求最每一层最右边的节点
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> rightSideView(TreeNode root) {
// 记录答案
List<Integer> ans = new ArrayList<Integer>();
if (root == null) return ans;
// 层序遍历, 选择最右侧节点
Deque<TreeNode> deque = new ArrayDeque<TreeNode>();
deque.add(root);
while(!deque.isEmpty()) {
int cnt = deque.size();
TreeNode last = null;
while(cnt-- > 0) {
TreeNode node = deque.pollFirst();
if (node.left != null)
deque.add(node.left);
if (node.right != null)
deque.add(node.right);
last = node;
}
ans.add(last.val);
}
return ans;
}
}