199. 二叉树的右视图
给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
中等难度。这道题所谓的右视图,实际上就是求二叉树的每一层的最右侧节点。那么最简单的是我们使用从右到左的BFS层序遍历即可,获取每一层的第一个节点并加入结果集合。
public ListrightSideView(TreeNode root) { LinkedList res = new LinkedList<>(); if (root == null) { return res; } LinkedList queue = new LinkedList<>(); queue.addLast(root); while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { root = queue.removeFirst(); //第一个元素 if (i == 0) { res.addLast(root.val); } //从右到左中序遍历 if (root.right != null) { queue.addLast(root.right); } if (root.left != null) { queue.addLast(root.left); } } } return res; }
另一种方式是使用DFS深度优先遍历,同样对于每一层的第一个节点加入结果集即可。
Listres = new ArrayList<>(); public List rightSideView(TreeNode root) { dfs(root, 0); return res; } void dfs(TreeNode root, int depth) { if (root == null) { return; } //如果当前层深度等于结果集数量,则说明当前节点是当前层的最右节点 if (depth == res.size()) { res.add(root.val); } depth++; dfs(root.right, depth); dfs(root.left, depth); }



