Contents

# 199. Binary Tree Right Side View

## 題目 :

Given the root of 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 :

Note

Example 1:

Input: root = [1,2,3,null,5,null,4] Output: [1,3,4]

Example 2:

Input: root = [1,null,3] Output: [1,3]

Example 3:

Input: root = [] Output: []

#### 解題思路 :

• 這題是level order traversal的變化題，一樣可以用queue來解決，可以參考 leetcode102題解
• 只需要取每個level最右邊的node

### Queue解法

• time complexity: O(n) , space complexity: O(n)

Runtime: 0 ms, faster than 100.00% of Go online submissions for Binary Tree Right Side View.

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 `````` ``````/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func rightSideView(root *TreeNode) []int { var res []int if root == nil { return res } var queue []*TreeNode queue = append(queue, root) for len(queue) != 0 { res = append(res, queue[len(queue)-1].Val) length := len(queue) for i := 0; i < length; i++ { node := queue if node.Left != nil { queue = append(queue, node.Left) } if node.Right != nil { queue = append(queue, node.Right) } queue = queue[1:] } } return res } ``````