题目描述
Leetcode 199 给定一个二叉树,返回从上到下每一行最右边的节点
题目思路
基本思路就是层级遍历整个树,然后将每一行最后一个元素插入结果
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
// BFS层级遍历
vector<int> res;
if (!root) return res;
queue<TreeNode*> q;
q.push(root);
while (q.size()) {
int n = q.size();
for (int i=0; i<n; i++) {
auto cur = q.front();
q.pop();
if (i==n-1) res.push_back(cur->val);
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
}
return res;
}
};
时间复杂度: N是所有节点个数
空间复杂度: M为队列中节点数,一般等于单层最多节点的个数