0%

[Leetcode]199. Binary Tree Right Side View(C++)

题目描述

题目链接:199. Binary Tree Right Side View

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.

例子

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation: see from problem description in LeetCode

解题思路

使用 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
#include <vector>
#include <queue>

class Solution {
public:
std::vector<int> rightSideView(TreeNode* root) {
std::vector<int> result;
if (root == nullptr) return result;
std::queue<TreeNode*> current_level;
current_level.push(root);
while (!current_level.empty()) {
std::queue<TreeNode*> next_level;
while(!current_level.empty()) {
TreeNode* node = current_level.front();
current_level.pop();
// only push the rightmost node to result
if (current_level.empty()) result.push_back(node->val);
if (node->left) next_level.push(node->left);
if (node->right) next_level.push(node->right);
}
current_level = next_level;
}
return result;
}
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(w)

GitHub 代码同步地址: 199.BinaryTreeRightSideView.cpp

其他题目:
GitHub: Leetcode-C++-Solution
博客: Leetcode-Solutions