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

[Leetcode] Binary Tree Right Side View

时间:2015-04-05 01:12:03      阅读:193      评论: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].

层次遍历。

 1 /**
 2  * Definition for binary tree
 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) return res;
15         queue<TreeNode*> Q;
16         TreeNode *p;
17         Q.push(root);
18         int cnt1 = 1, cnt2;
19         while (!Q.empty()) {
20             cnt2 = 0;
21             for (int i = 0; i < cnt1; ++i) {
22                 p = Q.front();
23                 Q.pop();
24                 if (i == cnt1 - 1) res.push_back(p->val);
25                 if (p->left) {
26                     Q.push(p->left);
27                     ++cnt2;
28                 }
29                 if (p->right) {
30                     Q.push(p->right);
31                     ++cnt2;
32                 }
33             }
34             cnt1 = cnt2;
35         }
36         return res;
37     }
38 };

 

[Leetcode] Binary Tree Right Side View

标签:

原文地址:http://www.cnblogs.com/easonliu/p/4393265.html

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