199. Binary Tree Right Side View** https://leetcode.com/problems/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 ordere
199. Binary Tree Right Side View**
https://leetcode.com/problems/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.
Example:
Input: [1,2,3,null,5,null,4]Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---
C++ 实现 1
层序遍历, 先存入右孩子即可.
class Solution {public:
vector<int> rightSideView(TreeNode* root) {
if (!root) return {};
queue<TreeNode*> q;
q.push(root);
vector<int> res;
while (!q.empty()) {
auto size = q.size();
for (int i = 0; i < size; ++ i) {
auto r = q.front();
q.pop();
if (i == 0) res.push_back(r->val);
if (r->right) q.push(r->right);
if (r->left) q.push(r->left);
}
}
return res;
}
};
C++ 实现 2
另外这题使用 DFS 也可以完成, 在 dfs 中先遍历右子树, 再遍历左子树. 使用 max_depth 记录当前访问的最大深度, 如果 depth > max_depth 时, 对 max_depth 和 res 进行更新.
class Solution {private:
vector<int> res;
int max_depth = 0;
void dfs(TreeNode *root, int depth) {
if (!root) return;
if (depth > max_depth) {
max_depth = depth;
res.push_back(root->val);
}
dfs(root->right, depth + 1);
dfs(root->left, depth + 1);
}
public:
vector<int> rightSideView(TreeNode* root) {
if (!root) return {};
res.push_back(root->val);
dfs(root, 0);
return res;
}
};