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),考虑最坏情况树变成链表;
相关文章推荐
- [LeetCode] 199. Binary Tree Right Side View 二叉树的右侧视图
- LeetCode 199. Binary Tree Right Side View(二叉树右侧视图)
- [LeetCode] Binary Tree Right Side View 二叉树的右侧视图
- [LeetCode题解] 199. 二叉树的右视图
- 利用python 完成 leetcode 199 二叉树的右视图
- 右侧视角的二叉树
- LeetCode题解之填充二叉树中每个节点的下一个右侧节点
- IIS里面是空的,没有"默认网站",右侧提示“此视图中没有可显示的项目”
- 【Leetcode】199. 二叉树的右视图
- [和小菜鸡一起刷题(python)] LeetCode 199. 二叉树的右视图. (Binary Tree Right Side View)
- Leetcode 199. 二叉树的右视图
- leetcode-二叉树右视图(python)
- 二叉树层序遍历应用:要求将所有结点加上一个m_pNext指针,指向同层右侧的结点,右侧若无结点则指向NULL,写出其中的Connect函数。
- Leetcode 199 Binary Tree Right Side View 二叉树右视图
- leetcode-199. 二叉树的右视图
- Leetcode 116 Populating Next Right Pointers in Each Node 二叉树填充next指针指向右侧结点
- Leetcode 199 Binary Tree Right Side View 二叉树右视图
- LeetCode 199.二叉树的右视图(dfs,如果是数组实现树)
- IOS开发仿微信右侧弹出视图实现
- UITableViewCell 消除右侧辅助视图区域空白