Files
LeetCode-Go/website/content/ChapterFour/0100~0199/0199.Binary-Tree-Right-Side-View.md
2021-06-01 22:52:00 +08:00

82 lines
1.7 KiB
Markdown

# [199. Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/)
## 题目
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 <---
```
## 题目大意
从右边看一个树,输出看到的数字。注意有遮挡。
## 解题思路
- 这一题是按层序遍历的变种题。按照层序把每层的元素都遍历出来,然后依次取每一层的最右边的元素即可。用一个队列即可实现。
- 第 102 题和第 107 题都是按层序遍历的。
## 代码
```go
package leetcode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func rightSideView(root *TreeNode) []int {
res := []int{}
if root == nil {
return res
}
queue := []*TreeNode{root}
for len(queue) > 0 {
n := len(queue)
for i := 0; i < n; i++ {
if queue[i].Left != nil {
queue = append(queue, queue[i].Left)
}
if queue[i].Right != nil {
queue = append(queue, queue[i].Right)
}
}
res = append(res, queue[n-1].Val)
queue = queue[n:]
}
return res
}
```
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0100~0199/0198.House-Robber/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0200~0299/0200.Number-of-Islands/">下一页➡️</a></p>
</div>