Created
March 2, 2020 17:31
-
-
Save alldroll/f52ca50e5670431ad1871bfd30d44f4c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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