199. Binary Tree Right Side View

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

For example:
Given the following binary tree,

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

 

You should return [1, 3, 4].

题目含义:从右面观察一颗二叉树,输出由上到下打印的节点

复制代码
 1     public List<Integer> rightSideView(TreeNode root) {
 2         List<Integer> result = new ArrayList<>();
 3         if (root == null) return result;
 4         Queue<TreeNode> q = new LinkedList<>();
 5         q.add(root);
 6         while (!q.isEmpty())
 7         {
 8             int size = q.size();
 9             TreeNode node = null;
10             for (int i=0;i<size;i++)
11             {
12                 node = q.poll();
13                 if (node.left !=null) q.offer(node.left);
14                 if (node.right !=null) q.offer(node.right);
15             }
16             result.add(node.val);
17         }
18         return result;        
19     }
复制代码

 

posted @   daniel456  阅读(159)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示