码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Right Side View

时间:2015-06-25 12:10:27      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:

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

 

Binary Tree Right Side View

标签:

原文地址:http://www.cnblogs.com/happygirl-zjj/p/4599514.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!