From 059b6464c0b8968bd139764988ecbc652eebdabe Mon Sep 17 00:00:00 2001 From: "Zhen (Evan) Wang" <273509239@qq.com> Date: Tue, 14 Jan 2025 10:36:56 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200102.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86--199.?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84=E5=8F=B3=E8=A7=86=E5=9B=BE?= =?UTF-8?q?=20=20C#=20=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0102.二叉树的层序遍历中的199.二叉树的右视图 C# 代码 --- problems/0102.二叉树的层序遍历.md | 41 +++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 98e1e98a..0c3b0f8c 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -1231,6 +1231,47 @@ impl Solution { } ``` +#### C#: + +```C# 199.二叉树的右视图 +public class Solution +{ + public IList RightSideView(TreeNode root) + { + var result = new List(); + Queue queue = new(); + + if (root != null) + { + queue.Enqueue(root); + } + while (queue.Count > 0) + { + int count = queue.Count; + int lastValue = count - 1; + for (int i = 0; i < count; i++) + { + var currentNode = queue.Dequeue(); + if (i == lastValue) + { + result.Add(currentNode.val); + } + + // lastValue == i == count -1 : left 先于 right 进入Queue + if (currentNode.left != null) queue.Enqueue(currentNode.left); + if (currentNode.right != null) queue.Enqueue(currentNode.right); + + //// lastValue == i == 0: right 先于 left 进入Queue + // if(currentNode.right !=null ) queue.Enqueue(currentNode.right); + // if(currentNode.left !=null ) queue.Enqueue(currentNode.left); + } + } + + return result; + } +} +``` + ## 637.二叉树的层平均值 [力扣题目链接](https://leetcode.cn/problems/average-of-levels-in-binary-tree/)