首页 > 其他 > 详细

[LC] 199. Binary Tree Right Side View

时间:2019-12-07 12:59:04      阅读:73      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!