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

[LC] 199. Binary Tree Right Side View

时间:2019-12-07 12:18:43      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:elf   ++   input   empty   exp   array   can   amp   nbsp   

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.

Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

   1            <---
 /   2     3         <---
 \       5     4       <---

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public List<Integer> rightSideView(TreeNode root) {
12         List<Integer> res = new ArrayList<>();
13         Queue<TreeNode> queue = new LinkedList<>();
14         if (root == null) {
15             return res;
16         }
17         queue.offer(root);
18         while (!queue.isEmpty()) {
19             int size = queue.size();
20             for (int i = 0; i < size; i++) {
21                 TreeNode cur = queue.poll();
22                 if (i == 0) {
23                     res.add(cur.val);
24                 }
25                 if (cur.right != null) {
26                     queue.offer(cur.right);
27                 }
28                 if (cur.left != null) {
29                     queue.offer(cur.left);
30                 }
31             }
32         }
33         return res;
34     }
35 }

 

[LC] 199. Binary Tree Right Side View

标签:elf   ++   input   empty   exp   array   can   amp   nbsp   

原文地址:https://www.cnblogs.com/xuanlu/p/12001064.html

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