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

199. Binary Tree Right Side View

时间:2017-06-25 23:12:51      阅读:297      评论:0      收藏:0      [点我收藏+]

标签:判断   integer   example   lines   题目   while   following   ret   链接   

题目:

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

链接: http://leetcode.com/problems/binary-tree-right-side-view/

6/25/2017

2ms, 31%

注意,

1. linkedlist的几个常见方法

2. added可以不需要,只需要判断i== 0就可以了

 1 public class Solution {
 2     public List<Integer> rightSideView(TreeNode root) {
 3         List<Integer> ret = new ArrayList<Integer>();
 4         if (root == null) {
 5             return ret;
 6         }
 7         
 8         Queue<TreeNode> queue = new LinkedList<TreeNode>();
 9         queue.offer(root);
10         while (!queue.isEmpty()) {
11             boolean added = false;
12             int size = queue.size();
13             for (int i = 0; i < size; i++) {
14                 TreeNode tmp = queue.poll();
15                 if (!added) {
16                     ret.add(tmp.val);
17                     added = true;
18                 }
19                 if (tmp.right != null) {
20                     queue.add(tmp.right);
21                 }
22                 if (tmp.left != null) {
23                     queue.add(tmp.left);
24                 }
25             }
26         }
27         return ret;
28     }
29 }

别人的算法

recursive,但是很聪明的算法,尤其是判断是否要加入result的时候

https://discuss.leetcode.com/topic/11768/my-simple-accepted-solution-java

devide & conquer,没看懂

https://discuss.leetcode.com/topic/11302/java-solution-using-divide-and-conquer

Python

https://discuss.leetcode.com/topic/16164/5-9-lines-python-48-ms

更多讨论

https://discuss.leetcode.com/category/207/binary-tree-right-side-view

199. Binary Tree Right Side View

标签:判断   integer   example   lines   题目   while   following   ret   链接   

原文地址:http://www.cnblogs.com/panini/p/7078294.html

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