【LeetCode-面试算法经典-Java实现】【199-Binary Tree Right Side View(从右边看二叉树)】
来源:互联网 发布:c语言程序的基本单位 编辑:程序博客网 时间:2024/05/22 17:17
【199-Binary Tree Right Side View(从右边看二叉树】
【LeetCode-面试算法经典-Java实现】【所有题目目录索引】
代码下载【https://github.com/Wang-Jun-Chao】
原题
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].
题目大意
给定一个二叉树,想象自己站在树的右边,返回从下到下你能看到的节点的值。
解题思路
二叉树的层次遍历,每层按照从左向右的顺序依次访问节点,(每一层取最右边的结点)
代码实现
树结点类
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> result = new LinkedList<>(); if (root != null) { Deque<TreeNode> deque = new LinkedList<>(); // 当前层的结点数 int current = 1; // 下一层的结点数 int next = 0; TreeNode node; deque.addLast(root); while (deque.size() > 0) { // 取第一个结点 node = deque.removeFirst(); current--; // 添加非空的左结点 if (node.left != null) { next++; deque.addLast(node.left); } // 添加非空的右结点 if (node.right != null) { next++; deque.addLast(node.right); } // 如果当前层已经处理完了 if (current == 0) { // 保存此层的最右一个结点值 result.add(node.val); // 设置下一层的元素个数 current = next; next = 0; } } } return result; }}
评测结果
点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。
特别说明
欢迎转载,转载请注明出处【http://blog.csdn.net/derrantcm/article/details/47970785】
2 1
- 【LeetCode-面试算法经典-Java实现】【199-Binary Tree Right Side View(从右边看二叉树)】
- 199. Binary Tree Right Side View | 从右边看二叉树得到的集合
- Leetcode: Binary Tree Right Side View (Java)
- [leetcode] 199 Binary Tree Right Side View
- leetcode-199 Binary Tree Right Side View
- 199Binary 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
- Binary Tree Right Side View - LeetCode 199
- leetcode[199]:Binary Tree Right Side View
- 【Leetcode】Binary Tree Right Side View #199
- 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
- LeetCode 199 Binary Tree Right Side View
- Leecode_Missing number
- Leetcode: Flatten Binary Tree to Linked List
- POJ 3645 解题报告
- 【LeetCode-面试算法经典-Java实现】【198-House Robber(抢劫犯)】
- Spring MVC MultiActionController example
- 【LeetCode-面试算法经典-Java实现】【199-Binary Tree Right Side View(从右边看二叉树)】
- Spring MVC MultiActionController annotation example
- 【LeetCode-面试算法经典-Java实现】【200-Number of Islands(岛的数目)】
- Spring MVC PropertiesMethodNameResolver example
- 正则表达式测试工具 regexbuddy
- HDU 3625 Examining the Rooms(第一类斯特林数)
- 轻松python文本专题-单独处理字符串每个字符的方法汇总
- C语言的标准库概述
- Exactly-once Spark Streaming from Apache Kafka