199. Binary Tree Right Side View
阿新 • • 發佈:2017-06-26
boolean des empty vid sin using tom als null .
題目:
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