题目

给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

示例

输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

分析

本题可以看成是求二叉树每层的最后一个数据组成的数组。

题解

/**
 * 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) {
	if (!root) return [];
	let arr = []; // 暂存每层数据
	let res = []; // 存储每层最后一个数据
	arr.push(root);
	while (arr.length > 0) {
		res.push(arr[arr.length - 1].val); //将每层最后一个数据存入数组
		let len = arr.length;
		while (len > 0) {
			let now = arr.shift();
			if (now.left != null) arr.push(now.left);
			if (now.right != null) arr.push(now.right);
			len--;
		}
	}
	return res;
};