[LC] 199. Binary Tree Right Side View

Posted xuanlu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LC] 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.

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的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 199 :Binary Tree Right Side View

[LeetCode] 199. Binary Tree Right Side View

199. Binary Tree Right Side View

199. Binary Tree Right Side View

leetcode@ [199] Binary Tree Right Side View (DFS/BFS)

LC.110. Balanced Binary Tree