二叉树的右视图(Binary Tree Right Side View)
LeetCode传送门199. Binary Tree Right Side View
题目
给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
Given the root of 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: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
Input: root = [1,null,3]
Output: [1,3]
Input: root = []
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 100]. -100 <= Node.val <= 100
思考线
解题思路
看到这样一道题,我首先想到的是广度优先搜索(BFS),这样每次到达层级的末尾我们把结果放到res数组中,遍历完成返回res即可
代码如下
function rightSideView(root: TreeNode | null): number[] {
if(!root) return [];
const res = [];
let stack = [root];
let temp = [];
while(stack.length) {
res.push(stack[stack.length-1].val)
temp = [];
stack.forEach( (node, index) => {
if(node.left) temp.push(node.left);
if(node.right) temp.push(node.right);
})
stack = temp;
}
return res;
};
这道题也可以使用深度优先搜索(DFS),由于没有广度优先适合,在这里我就不展开了。