console.log('点个关注再走吧🍺');|

Tod4

园龄:2年11个月粉丝:21关注:0

[199. 二叉树的右视图]

199. 二叉树的右视图

给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

示例 1:

image-20230614104208993

输入: [1,2,3,null,5,null,4]
输出: [1,3,4]

示例 2:

输入: [1,null,3]
输出: [1,3]

示例 3:

输入: []
输出: []

提示:

  • 二叉树的节点个数的范围是 [0,100]
  • -100 <= Node.val <= 100
BFS层序遍历
  • 容易想到,遍历n个节点时间复杂度O(n)
class Solution {
public List<Integer> rightSideView(TreeNode root) {
var ans = new ArrayList<Integer>();
if(root == null) {
return ans;
}
Deque<TreeNode> que = new LinkedList<>();
que.add(root);
while(!que.isEmpty()) {
var size = que.size();
var last = -101;
while(size-- > 0) {
var poll = que.poll();
if(poll.left != null) {
que.add(poll.left);
}
if(poll.right != null) {
que.add(poll.right);
}
last = poll.val;
}
if(last != -101) {
ans.add(last);
}
}
return ans;
}
}
DFS
  • 遍历n个节点时间复杂度O(n),但是比层序遍历少了队列维护的时间
  • 先遍历右子树再遍历左子树,然后将深度第一次出现的节点放入结果集,则该即为该层的第一个最右边的节点
class Solution {
List<Integer> ans = new ArrayList<>();
public void dfs(TreeNode root, int depth) {
if(root == null) {
return ;
}
if(depth == ans.size()) {
ans.add(root.val);
}
dfs(root.right, depth + 1);
dfs(root.left, depth + 1);
}
public List<Integer> rightSideView(TreeNode root) {
dfs(root, 0);
return ans;
}
}
posted @   Tod4  阅读(13)  评论(0编辑  收藏  举报
历史上的今天:
2022-06-14 【Python爬虫(一)】XPath
2022-06-14 【书籍阅读】【Spring实战】二 装配Bean
   
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起