【LeetCode热题100(44/100)】二叉树的右视图
题目地址:链接
思路: 每层最后一个(层序遍历)最后一个压入数组
/*** Definition for a binary tree node.* function TreeNode(val, left, right) {* this.val = (val===undefined ? 0 : val)* this.left = (left===undefined ? null : left)* this.right = (right===undefined ? null : right)* }*/
/*** @param {TreeNode} root* @return {number[]}*/
var rightSideView = function(root) {if(!root) return [];let ans = [];let q = [root];let ceng = [];let last = true;while(q.length) {let node = q.shift();if(!node) continue;if(node.left) ceng.push(node.left);if(node.right)ceng.push(node.right);if(q.length == 0) {ans.push(node.val);q = [...ceng];ceng = [];last = true;}}return ans;
};