今天是2020年4月22日,星期三。
题目描述
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:
1 <---
/ \
2 3 <---
\ \
5 4 <---
题目分析
开始拿到题目的时候,感觉简单就是将右子树节点放进队列进行返回即可,但是转而一想发现,如果没有右子树,那么左子树就会被投影到左边的墙上,所以不能简单的将右子树节点放入结果集中进行处理。
经过观察可以发现,在右视图中,每一层都是最右侧的元素被投影到左面的墙上,那么我们可以采用BFS的方法按层次遍历,记录每一层的最右面的元素,即是我们所求的结果。
除了上面讲到的BFS的方法,在LeetCode的甜姨题解中还讲到了一种DFS的方法,原文地址:「二叉树的右视图」。在DFS中,要求右视图,则需要按照「根节点-右子树-左子树」的顺序访问,保证我们每次访问到的节点是右边的节点,与经常使用的先序遍历「根节点-左子树-右子树」的遍历顺序相反。
参考代码
- BFS层次遍历参考代码
class Solution {
public List<Integer> rightSideView(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}
List<Integer> result = new ArrayList<>();
if (root.left == null && root.right == null) {
result.add(root.val);
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode treeNode = queue.poll();
if (treeNode.left != null) {
queue.offer(treeNode.left);
}
if (treeNode.right != null) {
queue.offer(treeNode.right);
}
if (i + 1 == size) {
result.add(treeNode.val);
}
}
}
return result;
}
}
复杂度分析:
- 时间复杂度:O(N),每个节点均只遍历了一次。
- 空间复杂度:O(N),额外借助了队列空间进行存储。
- DFS遍历参考代码
class Solution {
public List<Integer> rightSideView(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}
List<Integer> result = new ArrayList<>();
if (root.left == null && root.right == null) {
result.add(root.val);
return result;
}
dfs(result, root, 0);
return result;
}
private void dfs(List<Integer> list, TreeNode node, int depth) {
if (node == null) {
return;
}
// 先访问根节点 -》 右子树节点 -》 左子树节点
// 如果当前节点所在深度还没有出现在res里,说明在该深度下当前节点是第一个被访问的节点,
// 又因为每次我们先访问右子树,所以当前节点一定是最右面的一个节点,因此将当前节点加入res中。
if (depth == list.size()) {
list.add(node.val);
}
depth++;
dfs(list, node.right, depth);
dfs(list, node.left, depth);
}
}
复杂度分析:
- 时间复杂度:O(N),每个节点均只遍历了一次。
- 空间复杂度:O(N),因为这棵树不是一棵平衡二叉树,二叉树的深度最少是logN,在最化的情况下回退化到N,因此递归时使用的栈空间是 O(N)。
774




被折叠的 条评论
为什么被折叠?



