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       <---


二叉树的右视图

C++:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<int> rightSideView(TreeNode* root) {
13         vector<int> res ;
14         if (root == NULL)
15             return res ;
16         queue<TreeNode*> q ;
17         q.push(root) ;
18         while(!q.empty()){
19             int len = q.size() ;
20             for(int i = 0 ; i < len ; i++){
21                 TreeNode* node = q.front() ;
22                 q.pop() ;
23                 if (node->left != NULL)
24                     q.push(node->left) ;
25                 if (node->right != NULL)
26                     q.push(node->right) ;
27                 if (i == len-1){
28                     res.push_back(node->val) ;
29                 }
30             }
31         }
32         return res ;
33     }
34 };
 
原文地址:https://www.cnblogs.com/mengchunchen/p/10599009.html