Skip to content

Instantly share code, notes, and snippets.

@alldroll
Created March 2, 2020 17:31
Show Gist options
  • Select an option

  • Save alldroll/f52ca50e5670431ad1871bfd30d44f4c to your computer and use it in GitHub Desktop.

Select an option

Save alldroll/f52ca50e5670431ad1871bfd30d44f4c to your computer and use it in GitHub Desktop.
// https://leetcode.com/problems/binary-tree-right-side-view
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type LevelNode struct {
node *TreeNode
level int
}
func rightSideView(root *TreeNode) []int {
if root == nil {
return []int{}
}
result := []int{}
queue := []*LevelNode{
&LevelNode{node: root, level: 1},
}
for len(queue) > 0 {
curr := queue[0]
queue = queue[1:]
if len(result) < curr.level {
result = append(result, curr.node.Val)
}
if curr.node.Right != nil {
queue = append(queue, &LevelNode{
node: curr.node.Right,
level: curr.level + 1,
})
}
if curr.node.Left != nil {
queue = append(queue, &LevelNode{
node: curr.node.Left,
level: curr.level + 1,
})
}
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment