Binary Tree Right Side View
来源:互联网 发布:自古枪兵幸运e 知乎 编辑:程序博客网 时间:2024/05/17 01:43
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].
思路:从右边看过去能看到的结点,也就是每一层最右边的结点,那么按照层序遍历,每一次遇到最右边的结点的时候就把它放到结果集中,可以用一个count来记录每一层的结点数。
/** * 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> result=new ArrayList<Integer>(); if(root==null) return result; ArrayDeque<TreeNode> queue=new ArrayDeque<TreeNode>(); queue.add(root); while(!queue.isEmpty()) { TreeNode temp=null; int count=queue.size(); for(int i=0;i<count;i++) { temp=queue.poll(); if(i==count-1) { result.add(temp.val); } if(temp.left!=null) queue.add(temp.left); if(temp.right!=null) queue.add(temp.right); } } return result; }}
0 0
- Binary Tree Right Side View
- Binary Tree Right Side View
- Binary Tree Right Side View
- Binary Tree Right Side View
- Binary Tree Right Side View
- Binary Tree Right Side View
- Binary Tree Right Side View
- Binary Tree Right Side View
- Binary Tree Right Side View
- Binary Tree Right Side View
- Binary Tree Right Side View
- Binary Tree Right Side View
- Binary Tree Right Side View
- Binary Tree Right Side View
- Binary Tree Right Side View
- Binary Tree Right Side View
- Binary Tree Right Side View
- Binary Tree Right Side View
- zend studio 10破解/汉化
- MySQL性能剖析
- Linux nohup守护进程经验
- 多个UIImage合并成一个UIImage
- hdu4576 Robot (概率DP)
- Binary Tree Right Side View
- zoj 1025 wooden sticks
- 南邮 OJ 1581 筷子
- Hdu 5344 MZL's xor 2015ACM多校对抗赛第五场
- Big Number
- HashMap Hash碰撞 treemap
- Delete Node in a Linked List
- Android内核学习之三----------Power源码分析学习(1)
- Catch That Cow SDUT 1028