# [LeetCode 199] 经典BFS,考虑倒序入队

其实正序和倒序差不多,但是倒序会“先”遇到右边的值。

function rightSideView(root: TreeNode | null): number[] {
  const res: number[] = [];
  if (!root) return res;
  const queue = [root];
  while (queue.length) {
    const length = queue.length;
    for (let i = 0; i < length; ++i) {
      const current = queue.pop()!;
      if (i === 0) res.push(current.val);
      if (current.right) queue.unshift(current.right);
      if (current.left) queue.unshift(current.left);
    }
  }
  return res;
}
最后更新于: 6/25/2020, 2:10:06 PM