Golang solution (3ms)


  • 0
    func rightSideView(root *TreeNode) []int {
        if root == nil { return nil }
        result, queue, numNodesAtLevel := []int{}, []*TreeNode{}, 1
        queue = append(queue, root)
        for len(queue) != 0 {
            node := queue[0]
            queue = queue[1:]
            numNodesAtLevel--
            if node.Left != nil { queue = append(queue, node.Left) }
            if node.Right != nil { queue = append(queue, node.Right) }
            if numNodesAtLevel == 0 {
                result = append(result, node.Val)
                numNodesAtLevel = len(queue)
            }
        }
        return result
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.