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

[leetcode 199]Binary Tree Right Side View

时间:2015-11-29 13:24:32      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

Question:

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

Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.

 

Subscribe to see which companies asked this question

 
Solution:
二叉树层次遍历(BFS)后保留最后一个node即可。
 1 vector<int> rightSideView(TreeNode* root) 
 2     {
 3         queue<TreeNode*> qtree;
 4         vector<int> result;
 5         vector<int> line_nodes;
 6         TreeNode *visit = NULL;
 7         int line_size = 1;
 8         int next_line_size = 0;
 9         
10         if (root == NULL)
11             return result;
12             
13         qtree.push(root);
14         while (!qtree.empty())
15         {
16             visit = qtree.front();
17             qtree.pop();
18             line_size--;
19             line_nodes.push_back(visit->val);
20             
21             if (visit->left)
22             {
23                 qtree.push(visit->left);
24                 next_line_size++;
25             }
26             if (visit->right)
27             {
28                 qtree.push(visit->right);
29                 next_line_size++;
30             }
31             
32             if (line_size == 0) 
33             {
34                 line_size = next_line_size;
35                 next_line_size = 0;
36                 result.push_back(line_nodes.back());
37                 line_nodes.clear();
38             }
39         }
40         
41         return result;
42     }

由于不需要返回每层的节点,可以如下优化:

 1 vector<int> rightSideView(TreeNode* root) 
 2     {
 3         queue<TreeNode*> qtree;
 4         vector<int> result;
 5         TreeNode *visit = NULL;
 6         
 7         if (root == NULL)
 8             return result;
 9             
10         qtree.push(root);
11         while (!qtree.empty())
12         {
13             visit = qtree.back();
14             result.push_back(visit->val);
15             int size = qtree.size();
16             for (int i = 0; i < size; i++)
17             {
18                 visit = qtree.front();
19                 qtree.pop();
20                 if (visit->left)
21                     qtree.push(visit->left);
22                 if (visit->right)
23                     qtree.push(visit->right);
24             }
25         }
26         
27         return result;
28     }

 

[leetcode 199]Binary Tree Right Side View

标签:

原文地址:http://www.cnblogs.com/ym65536/p/5004567.html

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