199. Binary Tree Right Side View

Difficulty:
Related Topics:
Similar Questions:

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

Solution (Java)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        recurse(root, 0, list);
        return list;
    }

    private void recurse(TreeNode node, int level, List<Integer> list) {
        if (node != null) {
            if (list.size() < level + 1) {
                list.add(node.val);
            }
            recurse(node.right, level + 1, list);
            recurse(node.left, level + 1, list);
        }
    }
}

Solution 1 (Javascript)

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var rightSideView = function(root) {
  var queue = [{ node: root, level: 0 }];
  var result = [];
  var now = null;
  while (now = queue.shift()) {
    if (!now.node) continue;
    result[now.level] = now.node.val;
    queue.push({ node: now.node.left, level: now.level + 1 });
    queue.push({ node: now.node.right, level: now.level + 1 });
  }
  return result;
};

Explain:

nope.

Complexity:

Solution 2 (Javascript)

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var rightSideView = function(root) {
  var result = [];
  helper(root, 0, result);
  return result;
};

var helper = function (node, level, result) {
  if (!node) return;
  result[level] = node.val;
  helper(node.left, level + 1, result);
  helper(node.right, level + 1, result);
};

Explain:

nope.

Complexity: