199. Binary Tree Right Side View #
Problem #
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 <---
Problem Summary #
Look at a tree from the right side and output the numbers you can see. Note that some nodes may be blocked from view.
Solution Ideas #
- This problem is a variation of level-order traversal. Traverse all elements of each level in level order, then take the rightmost element of each level in sequence. This can be implemented with a queue.
- Problems 102 and 107 are both level-order traversal problems.
Code #
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
}