1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
class Solution { public: vector<int> rightSideView(TreeNode* root) { if(!root) return {}; vector<int> ret; queue<TreeNode*> q; q.push(root); while(!q.empty()) { ret.push_back(q.back()->val); for(int i = 0, sz = q.size(); i < sz; ++i) { auto p = q.front(); q.pop(); if(p->left) q.push(p->left); if(p->right) q.push(p->right); } } return ret; } };
|
T(n) : O(n) S(n) : O(k)(k为每层数)
discussion的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
class Solution { public: vector<int> rightSideView(TreeNode* root) { vector<int> ret; rightView(ret, root, 0); return ret; } private: void rightView(vector<int>& ret, TreeNode* node, int depth) { if(!node) return; if(depth == ret.size()) ret.push_back(node->val); rightView(ret, node->right, depth + 1); rightView(ret, node->left, depth + 1); } };
|
O(logn) 总体思路是每层只添加一个,然后仅当每层没添加时才会添加进去,而层数通过ret的大小来判定,由于是从右到左遍历,因此每层添加的一定是最右的