您的位置:首页 > 其它

JZ046:二叉树的右侧视图

2022-05-11 23:02 9201 查看

title: 二叉树的右侧视图

📃 题目描述

题目链接:二叉树的右侧视图相同题目

🔔 解题思路

方法一:队列层次遍历(bfs)

class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
queue<TreeNode*> que;
if (root == nullptr) return res;
que.push(root);
while (!que.empty()) {
int size = que.size();
for (int i = 0; i < size; i++) {
TreeNode *node = que.front();
que.pop();
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
if (i == size - 1) res.push_back(node->val);
}
}
return res;
}
};

方法二:dfs

关键点:用一个depth记录一层的视点 节点是否找到

class Solution {
public:
vector<int> res;
vector<int> rightSideView(TreeNode* root) {
if (root == nullptr) return res;
dfs(root, 0);
return res;
}
void dfs(TreeNode *root, int depth) {
if (depth == res.size()) res.emplace_back(root->val);

if (root->right) dfs(root->right, depth + 1);
if (root->left) dfs(root->left, depth + 1);
}
};

💥 复杂度分析

  • 时间复杂度:o(n)
  • 空间复杂度:O(n),考虑最坏情况树变成链表;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: