Binary Tree Right Side View


#1

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       <---

#2

This problem can be solved by doing a level order traversal. We force the level order by passing the right sub tree first and then the left. When the length of the result array matches the level, we add the value to the result. This allows us not to add more than one value at each level.

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func rightSideView(root *TreeNode) []int {
    result := make([]int, 0)
    if(root==nil){return result}
    helper(root, 0, &result)
    return result
}

func helper(node *TreeNode, level int , result *[]int){
    if node==nil{ return }
    
    if level==len(*result){
        *result = append(*result, node.Val)
    }
    
    helper(node.Right, level+1, result)
    helper(node.Left, level+1, result)
}