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

Binary Tree Right Side View

时间:2015-04-10 06:32:46      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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

 

Binary Tree Right Side View

标签:

原文地址:http://www.cnblogs.com/gonuts/p/4413375.html

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