https://leetcode-cn.com/problems/binary-tree-right-side-view/
层序遍历,非常好写,只是先右再左。
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
queue<TreeNode *> q;
vector<int> res;
if (!root) {
return res;
}
q.push(root);
while (!q.empty()) {
int front_val = q.front()->val;
res.push_back(front_val);
int size = q.size();
for (int i = 0; i < size; i++){
TreeNode* node = q.front();
if (node->right) q.push(node->right);
if (node->left) q.push(node->left);
q.pop();
}
}
return res;
}
}
网友评论