[Leetcode] 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.

For example:
Given the following binary tree,

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

You should return [1, 3, 4].

层次遍历。

 1 /**
 2  * Definition for binary tree
 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) return res;
15         queue<TreeNode*> Q;
16         TreeNode *p;
17         Q.push(root);
18         int cnt1 = 1, cnt2;
19         while (!Q.empty()) {
20             cnt2 = 0;
21             for (int i = 0; i < cnt1; ++i) {
22                 p = Q.front();
23                 Q.pop();
24                 if (i == cnt1 - 1) res.push_back(p->val);
25                 if (p->left) {
26                     Q.push(p->left);
27                     ++cnt2;
28                 }
29                 if (p->right) {
30                     Q.push(p->right);
31                     ++cnt2;
32                 }
33             }
34             cnt1 = cnt2;
35         }
36         return res;
37     }
38 };
原文地址:https://www.cnblogs.com/easonliu/p/4393265.html