首页 > 其他 > 详细

LeetCode Binary Tree Right Side View

时间:2015-05-07 10:00:24      阅读:175      评论:0      收藏:0      [点我收藏+]

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.

 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         }
17         queue<TreeNode*> que;
18         que.push(root);
19         while (!que.empty()) {
20             int len = que.size();
21             res.push_back(que.back()->val);
22             for (int i=0; i<len; i++) {
23                 TreeNode* node = que.front();
24                 que.pop();
25                 if (node->left != NULL) {
26                     que.push(node->left);
27                 }
28                 if (node->right != NULL) {
29                     que.push(node->right);
30                 }
31             }
32         }
33         return res;
34     }
35 };

会不会有更简单的方法呢

LeetCode Binary Tree Right Side View

原文:http://www.cnblogs.com/lailailai/p/4483818.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!