•  LeetCode199:二叉树的右视图


    LeetCode199:二叉树的右视图

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

     

    示例 1:

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

    输出: [1,3,4]

    关键词:二叉树的层序遍历,队列(先进先出)

    思路:二叉树的右视图中的元素 等价于  二叉树的层序遍历中每一层的最后一个节点。

    基本步骤:准备一个栈,根节点入队,队列不为空的情况下一直执行以下操作:

    记录当前队列的大小(即同层节点的个数)。出队,如果当前出队元素是同层中的最后一个节点,就将此元素添加到结果链表res中。循环遍历队列中的TreeNode节点,如果节点存在左右子树,就将其左右子树加入到队列中。

    代码实现:

    1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * int val;
    5. * TreeNode left;
    6. * TreeNode right;
    7. * TreeNode() {}
    8. * TreeNode(int val) { this.val = val; }
    9. * TreeNode(int val, TreeNode left, TreeNode right) {
    10. * this.val = val;
    11. * this.left = left;
    12. * this.right = right;
    13. * }
    14. * }
    15. */
    16. class Solution {
    17. public List rightSideView(TreeNode root) {
    18. if (root == null) {
    19. return new ArrayList<>();
    20. }
    21. Queue queue = new LinkedList<>();
    22. List res = new LinkedList<>();
    23. queue.offer(root);
    24. while (!queue.isEmpty()) {
    25. int size = queue.size();
    26. for (int i = 0; i < size; ++i) {
    27. TreeNode cur = queue.poll();
    28. if (i == size - 1) {
    29. res.add(cur.val);
    30. }
    31. if (cur.left != null) {
    32. queue.offer(cur.left);
    33. }
    34. if (cur.right != null) {
    35. queue.offer(cur.right);
    36. }
    37. }
    38. }
    39. return res;
    40. }
    41. }

  • 相关阅读:
    实验记录:搭建网络过程
    RabbitMQ(安装配置以及与SpringBoot整合)
    设计-命令模式
    2022年0702 第八课 JAVA中的数据结构重中的集合
    echarts 树形图
    GFS分布式文件系统
    docker <容器数据卷 -v > -- 对容器内数据持久化(备份)
    通信达行情接口是什么意思?
    Spring Cloud GateWay基于nacos如何去做灰度发布
    SpringBoot+Netty+Vue+Websocket实现在线推送/聊天系统
  • 原文地址:https://blog.csdn.net/RitaAndWakaka/article/details/126384584