Binary Tree Right Side View

Description:

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

Code:

 1    vector<int> rightSideView(TreeNode *root) {
 2         deque<TreeNode*>a;
 3         deque<TreeNode*>b;
 4         vector<int>result;
 5         
 6         if (root==NULL)
 7             return result;
 8             
 9         a.push_back(root);
10         while ( !a.empty() || !b.empty() )
11         {
12             if ( !a.empty() )
13             {
14                 //去队首元素
15                 result.push_back(a.front()->val);
16                 //将a中所有元素的孩子存放到b中,并清空a
17                 while (!a.empty())
18                 {
19                     TreeNode* p = a.front();
20                     if (p->right)
21                         b.push_back(p->right);
22                     if (p->left)
23                         b.push_back(p->left);
24                     a.pop_front();
25                 }
26             }
27             else
28             {
29                 result.push_back(b.front()->val);
30                 //将a中所有元素的孩子存放到b中,并清空a
31                 while (!b.empty())
32                 {
33                     TreeNode* p = b.front();
34                     if (p->right)
35                         a.push_back(p->right);
36                     if (p->left)
37                         a.push_back(p->left);
38                     b.pop_front();
39                 }
40             }
41         }
42          return result;
43     }
View Code
原文地址:https://www.cnblogs.com/happygirl-zjj/p/4599514.html