bfs O(n) time O(n) space
bfs逐层遍历每次取最后一个即可
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) { if (!root) return {}; vector<int> res; list<TreeNode *> q; q.push_back(root); while (!q.empty()) { res.push_back(q.back()->val); for (int i = q.size(); i > 0; --i) { auto p = q.front(); q.pop_front(); if (p->left) { q.push_back(p->left); } if (p->right) { q.push_back(p->right); } } } return res; } };
|