首页 > 代码库 > 199. Binary Tree Right Side View

199. Binary Tree Right Side View

题目:

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