首页 > 其他 > 详细

leetcode------Binary Tree Right Side View

时间:2015-04-06 15:38:22      阅读:267      评论:0      收藏:0      [点我收藏+]
标题: Binary Tree Right Side View
通过率: 27.9%
难度: 中等

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].

 本题就是个按层次遍历的一种延伸,按层遍历时每次讲每一层的最后一个元素放入结果的list中即可,代码如下:

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public ArrayList<Integer> rightSideView(TreeNode root) {
12         ArrayList<Integer> res=new ArrayList<Integer>();
13         LinkedList<TreeNode> queue=new LinkedList<TreeNode>();
14         int count=1,tmp=0;
15         if(root==null)return res;
16         queue.addLast(root);
17         while(!queue.isEmpty()){
18             tmp=0;
19             for(int i=1;i<=count;i++){
20                 TreeNode tmptree=queue.removeFirst();
21                 if(i==count)res.add(tmptree.val);
22                 if(tmptree.left!=null){
23                     queue.addLast(tmptree.left);
24                     tmp++;
25                 }
26                 if(tmptree.right!=null){
27                     queue.addLast(tmptree.right);
28                     tmp++;
29                 }
30                 
31             }
32             count=tmp;
33         }
34         return res;
35     }
36 }

 

leetcode------Binary Tree Right Side View

原文:http://www.cnblogs.com/pkuYang/p/4395999.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!