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 1

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

/**
 * 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: