码迷,mamicode.com
首页 > 其他好文 > 详细

199. Binary Tree Right Side View -----层序遍历

时间:2018-02-01 14:43:22      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:==   yourself   tom   pos   for   public   post   integer   color   

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

 

其实就是层序遍历 的每层的最后一个元素!!!!

 1 class Solution {
 2     
 3     public List<Integer> rightSideView(TreeNode root) {
 4         List<Integer> res = new ArrayList<Integer>();
 5         Queue<TreeNode> queue = new LinkedList<TreeNode>();
 6         if(root==null) return res;
 7         queue.offer(root);
 8         int level_num = 1;
 9         while (!queue.isEmpty()) {
10             level_num = queue.size();
11             for(int i = 0; i < level_num; i++){
12                 TreeNode node = queue.poll();
13                 if(i==level_num-1)
14                     res.add(node.val);
15                 if(node.left != null) queue.offer(node.left);
16                 if(node.right != null) queue.offer(node.right);
17                 
18             }
19         }
20         return res;
21     }
22 }

 

199. Binary Tree Right Side View -----层序遍历

标签:==   yourself   tom   pos   for   public   post   integer   color   

原文地址:https://www.cnblogs.com/zle1992/p/8398387.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!