Algorithm/src/main/java/tree/RightSideView.java
2025-03-24 18:58:37 +08:00

37 lines
1.1 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package tree;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
/**
* 题目: 199. 二叉树的右视图 (rightSideView)
* 描述:给定一个二叉树的 根节点 root想象自己站在它的右侧按照从顶部到底部的顺序返回从右侧所能看到的节点值。
* 链接https://leetcode.cn/problems/binary-tree-right-side-view/description/
*/
public class RightSideView {
public List<Integer> rightSideView(TreeNode root) {
Queue<TreeNode>queue=new ArrayDeque<>();
List<Integer>res=new ArrayList<>();
if(root==null)
return res;
queue.offer(root);
while (!queue.isEmpty()){
int size=queue.size();
for (int i = 0; i < size; i++) {
TreeNode temp=queue.poll();
if(i==size-1)
res.add(temp.val);
if(temp.left!=null)
queue.offer(temp.left);
if(temp.right!=null)
queue.offer(temp.right);
}
}
return res;
}
}