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

LeetCode OJ:Binary Tree Right Side View(右侧视角下的二叉树)

时间:2015-10-24 12:44:28      阅读:187      评论: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].

其实题目的意思就是相当于二叉树每一行的最右边的一个元素,那么简单,先bfs后取每一个数组的最后一位数就可以了,代码如下:

 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         int dep = -1;
14         bfs(root, dep + 1);
15         vector<int> res;
16         for(int i = 0; i < ret.size(); ++i){
17             res.push_back(ret[i][ret[i].size() - 1]);
18         }
19         return res;
20     }
21 
22     void bfs(TreeNode * root, int depth)
23     {
24         if(root == NULL) return;
25         if(depth < ret.size()){
26             ret[depth].push_back(root->val);
27         }else{
28             vector<int>tmp;
29             ret.push_back(tmp);
30             ret[depth].push_back(root->val);
31         }
32         if(root->left)
33             bfs(root->left, depth + 1);
34         if(root->right)
35             bfs(root->right, depth + 1);
36     }
37 private:
38     vector<vector<int>> ret;
39 };

 

LeetCode OJ:Binary Tree Right Side View(右侧视角下的二叉树)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4906486.html

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