199. Binary Tree Right Side View | 从右边看二叉树得到的集合
来源:互联网 发布:国语电影排行榜 知乎 编辑:程序博客网 时间:2024/06/11 06:58
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]
.
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
Subscribe to see which companies asked this question.
思路:广度优先遍历,用队列层次遍历,并记录每层的个数,当遍历到最后一个的时候就添加到结果集合中,最后返回结果。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public List<Integer> rightSideView(TreeNode root) {List<Integer> list = new ArrayList<>();if (root == null) {return list;}LinkedList<TreeNode> queue = new LinkedList<>();queue.push(root);int next = 0, num = 1;while (!queue.isEmpty()) {TreeNode treeNode = queue.poll();num--;if (treeNode.left != null) {queue.addLast(treeNode.left);next++;}if (treeNode.right != null) {queue.addLast(treeNode.right);next++;}if (num == 0) {list.add(treeNode.val);num = next;next = 0;}}return list;}}
0 0
- 199. Binary Tree Right Side View | 从右边看二叉树得到的集合
- 【LeetCode-面试算法经典-Java实现】【199-Binary Tree Right Side View(从右边看二叉树)】
- Binary Tree Right Side View 从左边视角输出二叉树的值
- Binary Tree Right Side View 二叉树:右视图
- Tree-----199. Binary Tree Right Side View
- LeetCode 199. Binary Tree Right Side View(二叉树右侧视图)
- 199.leetcode Binary Tree Right Side View(medium)[层次遍历二叉树 队列]
- LeetCode-199. Binary Tree Right Side View (JAVA)(二叉树最右侧结点)
- [LeetCode]199.Binary Tree Right Side View
- LeetCode 199. Binary Tree Right Side View
- [leetcode] 199.Binary Tree Right Side View
- [leetcode] 199. Binary Tree Right Side View
- [LeetCode]199. Binary Tree Right Side View
- 199. Binary Tree Right Side View LeetCode
- leetcode 199. Binary Tree Right Side View
- [LeetCode]199. Binary Tree Right Side View
- [LeetCode]199. Binary Tree Right Side View
- 199. Binary Tree Right Side View
- C++读取配置文件,重点是读取XML配置文件
- Python基础入门(三)- Python程序怎样运行
- javaIO file类
- 党的十八大光辉照亮了北京大学校园
- Linux误删C基本运行库libc.so.6急救方法
- 199. Binary Tree Right Side View | 从右边看二叉树得到的集合
- Lumen中使用JWT-Auth刷新token实现方式
- 欢迎使用CSDN-markdown编辑器
- react-native 实现条码扫描(ios&android)
- LeetCode | 18. 4Sum
- 完美解决 ERROR 1064 (42000): You have an error in your SQL syntax ... near …
- 动态规划练习06:登山
- SSM+JQuery+Ajax登录验证
- Android App 沉浸式状态栏解决方案