199 Binary Tree Right Side View 二叉树的右视图
2024-09-04 08:23:27
给定一棵二叉树,想象自己站在它的右侧,返回从顶部到底部看到的节点值。
例如:
给定以下二叉树,
1 <---
/ \
2 3 <---
\ \
5 4 <---
你应该返回 [1, 3, 4]。
详见:https://leetcode.com/problems/binary-tree-right-side-view/description/
Java实现:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res=new ArrayList<Integer>();
if(root==null){
return res;
}
LinkedList<TreeNode> que=new LinkedList<TreeNode>();
que.offer(root);
int node=1;
while(!que.isEmpty()){
root=que.poll();
--node;
if(root.left!=null){
que.offer(root.left);
}
if(root.right!=null){
que.offer(root.right);
}
if(node==0){
res.add(root.val);
node=que.size();
}
}
return res;
}
}
最新文章
- Rabin-Karp指纹字符串查找算法
- MySQL索引背后的数据结构及算法原理
- 问题导向VS目标导向:领导者要倾向哪种?
- Distinct删除重复数据时 自定义的方法比较【转】
- Roman to Integer -- LeetCode 13
- Kendo UI for ASP.NET MVC 的一些使用经验(转)
- php部分--面向对象三大特性-封装(另加连续调用的一个例子)、继承(重写、重载的例子)、多态;
- iBeacon 开发笔记
- HDU-1874 畅通工程续 (最短路径启蒙题)
- Property 和 Attribute 的区别(转)
- API模板
- 电脑移动后WIFI连接失败解决方法
- Flask 系列之 优化项目结构
- 弄懂Kafka的消息流转过程
- MySQL 查看用户授予的权限
- QPainter绘制渐进色文本
- 【shell编程】之基础知识-输入/输出和重定向
- Linux环境下查看线程数的几种方法
- Xamarin.Android之ListView和Adapter
- 10W年薪和30W+年薪的产品经理差距在哪?