199. 二叉树的右视图
给定一个二叉树的 根节点 root
,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例 1:
输入: [1,2,3,null,5,null,4]
输出: [1,3,4]
示例 2:
输入: [1,null,3]
输出: [1,3]
示例 3:
输入: []
输出: []
提示:
- 二叉树的节点个数的范围是
[0,100]
-100 <= Node.val <= 100
思路
102. 二叉树的层序遍历已经做过了分层遍历,只需要在分层遍历的基础上判断是否到达的该层的最后的一个节点即可。
解法
BFS分层遍历
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<>();
if(root == null){
return result;
}
Deque<TreeNode> deque = new LinkedList<>();
deque.offer(root);
while (!deque.isEmpty()) {
//获取当前层节点数量
int len = deque.size();
//从栈中将该层数据弹出
while (len > 0 && !deque.isEmpty()) {
root = deque.poll();
if(len == 1) {
result.add(root.val);
}
if (root.left != null) {
deque.offer(root.left);
}
if (root.right != null) {
deque.offer(root.right);
}
len--;
}
}
return result;
}
}
DFS递归
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> rightSideView(TreeNode root) {
traverse(root, 0);
return list;
}
public void traverse(TreeNode root, int depth) {
if(root == null){
return;
}
//先访问当前节点,再递归访问右子树和左子树
if(depth == list.size()){
//由于是先递归访问的的右子树,所以每一层的第一个节点就是该层的最右节点
list.add(root.val);
}
depth++;
traverse(root.right, depth);
traverse(root.left, depth);
}
}
DFS借助栈
同递归思路。如果知道每个节点的所在的深度,使用先遍历右子节点的方法,那么相同深度的第一个节点就是该层的最右节点。可以使用栈来维护遍历过程的节点和节点对应的深度。使用Map来进行判断该层节点是否已经被遍历过。最后将Map中的数据按所在层数从上到下依次输出即可。
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
int maxDepth = 0;
int curDepth = 0;
//存放节点
Stack<TreeNode> stack_data = new Stack<>();
//存放节点对应深度
Stack<Integer> stack_depth = new Stack<>();
//存放每层的最右节点
Map<Integer, TreeNode> map = new HashMap<>();
stack_data.push(root);
stack_depth.push(0);
map.put(0, root);
while (!stack_data.isEmpty()) {
root = stack_data.pop();
curDepth = stack_depth.pop();
maxDepth = Math.max(maxDepth, curDepth);
//如果当前层数据不存在,加入map中
map.putIfAbsent(curDepth, root);
curDepth++;
if (root.left != null) {
stack_data.push(root.left);
stack_depth.push(curDepth);
}
if (root.right != null) {
stack_data.push(root.right);
stack_depth.push(curDepth);
}
}
for (int i = 0; i <= maxDepth; i++) {
result.add(map.get(i).val);
}
return result;
}
}