1. 程式人生 > >199. Binary Tree Right Side View -----層序遍歷

199. Binary Tree Right Side View -----層序遍歷

span ott ane sta esc style stand you question

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 -----層序遍歷