199:二叉树的右视图

This commit is contained in:
huangge1199 2021-07-23 13:44:35 +08:00
parent 591223b339
commit 7e340e2f4e
2 changed files with 136 additions and 0 deletions

View File

@ -0,0 +1,100 @@
//给定一个二叉树的 根节点 root想象自己站在它的右侧按照从顶部到底部的顺序返回从右侧所能看到的节点值
//
//
//
// 示例 1:
//
//
//
//
//输入: [1,2,3,null,5,null,4]
//输出: [1,3,4]
//
//
// 示例 2:
//
//
//输入: [1,null,3]
//输出: [1,3]
//
//
// 示例 3:
//
//
//输入: []
//输出: []
//
//
//
//
// 提示:
//
//
// 二叉树的节点个数的范围是 [0,100]
// -100 <= Node.val <= 100
//
// Related Topics 深度优先搜索 广度优先搜索 二叉树
// 👍 502 👎 0
package leetcode.editor.cn;
import com.code.leet.entiy.TreeNode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
//199:二叉树的右视图
public class BinaryTreeRightSideView {
public static void main(String[] args) {
//测试代码
Solution solution = new BinaryTreeRightSideView().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
/**
* 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> list = new ArrayList<>();
if (root == null) {
return list;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 1; i <= size; i++) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
if (i == size) {
list.add(node.val);
}
}
}
return list;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,36 @@
<p>给定一个二叉树的 <strong>根节点</strong> <code>root</code>,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<p><img src="https://assets.leetcode.com/uploads/2021/02/14/tree.jpg" style="width: 270px; " /></p>
<pre>
<strong>输入:</strong> [1,2,3,null,5,null,4]
<strong>输出:</strong> [1,3,4]
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> [1,null,3]
<strong>输出:</strong> [1,3]
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong> []
<strong>输出:</strong> []
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>二叉树的节点个数的范围是 <code>[0,100]</code></li>
<li><meta charset="UTF-8" /><code>-100 <= Node.val <= 100</code> </li>
</ul>
<div><div>Related Topics</div><div><li></li><li>深度优先搜索</li><li>广度优先搜索</li><li>二叉树</li></div></div>\n<div><li>👍 502</li><li>👎 0</li></div>