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

LeetCode Binary Tree Right Side View

时间:2015-05-07 10:01:09      阅读:101      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!